babylon.viewer.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 17);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  83. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  84. (function universalModuleDefinition(root, factory) {
  85. var amdDependencies = [];
  86. var CANNON = root.CANNON;
  87. var OIMO = root.OIMO;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(20); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(21); } catch(e) {}
  91. module.exports = factory(CANNON,OIMO);
  92. } else if(typeof define === 'function' && define.amd) {
  93. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  94. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  95. define("babylonjs", amdDependencies, factory);
  96. } else if(typeof exports === 'object') {
  97. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  98. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  99. exports["babylonjs"] = factory(CANNON,OIMO);
  100. } else {
  101. root["BABYLON"] = factory(CANNON,OIMO);
  102. }
  103. })(this, function(CANNON,OIMO) {
  104. CANNON = CANNON || this.CANNON;
  105. OIMO = OIMO || this.OIMO;
  106. "use strict";
  107. var BABYLON;
  108. (function (BABYLON) {
  109. /**
  110. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  111. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  112. */
  113. var EffectFallbacks = /** @class */ (function () {
  114. function EffectFallbacks() {
  115. this._defines = {};
  116. this._currentRank = 32;
  117. this._maxRank = -1;
  118. }
  119. /**
  120. * Removes the fallback from the bound mesh.
  121. */
  122. EffectFallbacks.prototype.unBindMesh = function () {
  123. this._mesh = null;
  124. };
  125. /**
  126. * Adds a fallback on the specified property.
  127. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  128. * @param define The name of the define in the shader
  129. */
  130. EffectFallbacks.prototype.addFallback = function (rank, define) {
  131. if (!this._defines[rank]) {
  132. if (rank < this._currentRank) {
  133. this._currentRank = rank;
  134. }
  135. if (rank > this._maxRank) {
  136. this._maxRank = rank;
  137. }
  138. this._defines[rank] = new Array();
  139. }
  140. this._defines[rank].push(define);
  141. };
  142. /**
  143. * Sets the mesh to use CPU skinning when needing to fallback.
  144. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  145. * @param mesh The mesh to use the fallbacks.
  146. */
  147. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  148. this._mesh = mesh;
  149. if (rank < this._currentRank) {
  150. this._currentRank = rank;
  151. }
  152. if (rank > this._maxRank) {
  153. this._maxRank = rank;
  154. }
  155. };
  156. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  157. /**
  158. * Checks to see if more fallbacks are still availible.
  159. */
  160. get: function () {
  161. return this._currentRank <= this._maxRank;
  162. },
  163. enumerable: true,
  164. configurable: true
  165. });
  166. /**
  167. * Removes the defines that shoould be removed when falling back.
  168. * @param currentDefines defines the current define statements for the shader.
  169. * @param effect defines the current effect we try to compile
  170. * @returns The resulting defines with defines of the current rank removed.
  171. */
  172. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  173. // First we try to switch to CPU skinning
  174. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  175. this._mesh.computeBonesUsingShaders = false;
  176. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  177. var scene = this._mesh.getScene();
  178. for (var index = 0; index < scene.meshes.length; index++) {
  179. var otherMesh = scene.meshes[index];
  180. if (!otherMesh.material) {
  181. continue;
  182. }
  183. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  184. continue;
  185. }
  186. if (otherMesh.material.getEffect() === effect) {
  187. otherMesh.computeBonesUsingShaders = false;
  188. }
  189. else {
  190. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  191. var subMesh = _a[_i];
  192. var subMeshEffect = subMesh.effect;
  193. if (subMeshEffect === effect) {
  194. otherMesh.computeBonesUsingShaders = false;
  195. break;
  196. }
  197. }
  198. }
  199. }
  200. }
  201. else {
  202. var currentFallbacks = this._defines[this._currentRank];
  203. if (currentFallbacks) {
  204. for (var index = 0; index < currentFallbacks.length; index++) {
  205. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  206. }
  207. }
  208. this._currentRank++;
  209. }
  210. return currentDefines;
  211. };
  212. return EffectFallbacks;
  213. }());
  214. BABYLON.EffectFallbacks = EffectFallbacks;
  215. /**
  216. * Options to be used when creating an effect.
  217. */
  218. var EffectCreationOptions = /** @class */ (function () {
  219. function EffectCreationOptions() {
  220. }
  221. return EffectCreationOptions;
  222. }());
  223. BABYLON.EffectCreationOptions = EffectCreationOptions;
  224. /**
  225. * Effect containing vertex and fragment shader that can be executed on an object.
  226. */
  227. var Effect = /** @class */ (function () {
  228. /**
  229. * Instantiates an effect.
  230. * An effect can be used to create/manage/execute vertex and fragment shaders.
  231. * @param baseName Name of the effect.
  232. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  233. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  234. * @param samplers List of sampler variables that will be passed to the shader.
  235. * @param engine Engine to be used to render the effect
  236. * @param defines Define statements to be added to the shader.
  237. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  238. * @param onCompiled Callback that will be called when the shader is compiled.
  239. * @param onError Callback that will be called if an error occurs during shader compilation.
  240. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  241. */
  242. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  243. if (samplers === void 0) { samplers = null; }
  244. if (defines === void 0) { defines = null; }
  245. if (fallbacks === void 0) { fallbacks = null; }
  246. if (onCompiled === void 0) { onCompiled = null; }
  247. if (onError === void 0) { onError = null; }
  248. var _this = this;
  249. /**
  250. * Unique ID of the effect.
  251. */
  252. this.uniqueId = 0;
  253. /**
  254. * Observable that will be called when the shader is compiled.
  255. */
  256. this.onCompileObservable = new BABYLON.Observable();
  257. /**
  258. * Observable that will be called if an error occurs during shader compilation.
  259. */
  260. this.onErrorObservable = new BABYLON.Observable();
  261. /**
  262. * Observable that will be called when effect is bound.
  263. */
  264. this.onBindObservable = new BABYLON.Observable();
  265. this._uniformBuffersNames = {};
  266. this._isReady = false;
  267. this._compilationError = "";
  268. this.name = baseName;
  269. if (attributesNamesOrOptions.attributes) {
  270. var options = attributesNamesOrOptions;
  271. this._engine = uniformsNamesOrEngine;
  272. this._attributesNames = options.attributes;
  273. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  274. this._samplers = options.samplers.slice();
  275. this.defines = options.defines;
  276. this.onError = options.onError;
  277. this.onCompiled = options.onCompiled;
  278. this._fallbacks = options.fallbacks;
  279. this._indexParameters = options.indexParameters;
  280. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  281. if (options.uniformBuffersNames) {
  282. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  283. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  284. }
  285. }
  286. }
  287. else {
  288. this._engine = engine;
  289. this.defines = defines;
  290. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  291. this._samplers = samplers ? samplers.slice() : [];
  292. this._attributesNames = attributesNamesOrOptions;
  293. this.onError = onError;
  294. this.onCompiled = onCompiled;
  295. this._indexParameters = indexParameters;
  296. this._fallbacks = fallbacks;
  297. }
  298. this.uniqueId = Effect._uniqueIdSeed++;
  299. var vertexSource;
  300. var fragmentSource;
  301. if (baseName.vertexElement) {
  302. vertexSource = document.getElementById(baseName.vertexElement);
  303. if (!vertexSource) {
  304. vertexSource = baseName.vertexElement;
  305. }
  306. }
  307. else {
  308. vertexSource = baseName.vertex || baseName;
  309. }
  310. if (baseName.fragmentElement) {
  311. fragmentSource = document.getElementById(baseName.fragmentElement);
  312. if (!fragmentSource) {
  313. fragmentSource = baseName.fragmentElement;
  314. }
  315. }
  316. else {
  317. fragmentSource = baseName.fragment || baseName;
  318. }
  319. this._loadVertexShader(vertexSource, function (vertexCode) {
  320. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  321. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  322. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  323. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  324. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  325. if (baseName) {
  326. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  327. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  328. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  329. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  330. }
  331. else {
  332. _this._vertexSourceCode = migratedVertexCode;
  333. _this._fragmentSourceCode = migratedFragmentCode;
  334. }
  335. _this._prepareEffect();
  336. });
  337. });
  338. });
  339. });
  340. });
  341. });
  342. }
  343. Object.defineProperty(Effect.prototype, "key", {
  344. /**
  345. * Unique key for this effect
  346. */
  347. get: function () {
  348. return this._key;
  349. },
  350. enumerable: true,
  351. configurable: true
  352. });
  353. /**
  354. * If the effect has been compiled and prepared.
  355. * @returns if the effect is compiled and prepared.
  356. */
  357. Effect.prototype.isReady = function () {
  358. return this._isReady;
  359. };
  360. /**
  361. * The engine the effect was initialized with.
  362. * @returns the engine.
  363. */
  364. Effect.prototype.getEngine = function () {
  365. return this._engine;
  366. };
  367. /**
  368. * The compiled webGL program for the effect
  369. * @returns the webGL program.
  370. */
  371. Effect.prototype.getProgram = function () {
  372. return this._program;
  373. };
  374. /**
  375. * The set of names of attribute variables for the shader.
  376. * @returns An array of attribute names.
  377. */
  378. Effect.prototype.getAttributesNames = function () {
  379. return this._attributesNames;
  380. };
  381. /**
  382. * Returns the attribute at the given index.
  383. * @param index The index of the attribute.
  384. * @returns The location of the attribute.
  385. */
  386. Effect.prototype.getAttributeLocation = function (index) {
  387. return this._attributes[index];
  388. };
  389. /**
  390. * Returns the attribute based on the name of the variable.
  391. * @param name of the attribute to look up.
  392. * @returns the attribute location.
  393. */
  394. Effect.prototype.getAttributeLocationByName = function (name) {
  395. var index = this._attributesNames.indexOf(name);
  396. return this._attributes[index];
  397. };
  398. /**
  399. * The number of attributes.
  400. * @returns the numnber of attributes.
  401. */
  402. Effect.prototype.getAttributesCount = function () {
  403. return this._attributes.length;
  404. };
  405. /**
  406. * Gets the index of a uniform variable.
  407. * @param uniformName of the uniform to look up.
  408. * @returns the index.
  409. */
  410. Effect.prototype.getUniformIndex = function (uniformName) {
  411. return this._uniformsNames.indexOf(uniformName);
  412. };
  413. /**
  414. * Returns the attribute based on the name of the variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the location of the uniform.
  417. */
  418. Effect.prototype.getUniform = function (uniformName) {
  419. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  420. };
  421. /**
  422. * Returns an array of sampler variable names
  423. * @returns The array of sampler variable neames.
  424. */
  425. Effect.prototype.getSamplers = function () {
  426. return this._samplers;
  427. };
  428. /**
  429. * The error from the last compilation.
  430. * @returns the error string.
  431. */
  432. Effect.prototype.getCompilationError = function () {
  433. return this._compilationError;
  434. };
  435. /**
  436. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  437. * @param func The callback to be used.
  438. */
  439. Effect.prototype.executeWhenCompiled = function (func) {
  440. if (this.isReady()) {
  441. func(this);
  442. return;
  443. }
  444. this.onCompileObservable.add(function (effect) {
  445. func(effect);
  446. });
  447. };
  448. /** @ignore */
  449. Effect.prototype._loadVertexShader = function (vertex, callback) {
  450. if (BABYLON.Tools.IsWindowObjectExist()) {
  451. // DOM element ?
  452. if (vertex instanceof HTMLElement) {
  453. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  454. callback(vertexCode);
  455. return;
  456. }
  457. }
  458. // Base64 encoded ?
  459. if (vertex.substr(0, 7) === "base64:") {
  460. var vertexBinary = window.atob(vertex.substr(7));
  461. callback(vertexBinary);
  462. return;
  463. }
  464. // Is in local store ?
  465. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  466. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  467. return;
  468. }
  469. var vertexShaderUrl;
  470. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  471. vertexShaderUrl = vertex;
  472. }
  473. else {
  474. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  475. }
  476. // Vertex shader
  477. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  478. };
  479. /** @ignore */
  480. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  481. if (BABYLON.Tools.IsWindowObjectExist()) {
  482. // DOM element ?
  483. if (fragment instanceof HTMLElement) {
  484. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  485. callback(fragmentCode);
  486. return;
  487. }
  488. }
  489. // Base64 encoded ?
  490. if (fragment.substr(0, 7) === "base64:") {
  491. var fragmentBinary = window.atob(fragment.substr(7));
  492. callback(fragmentBinary);
  493. return;
  494. }
  495. // Is in local store ?
  496. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  497. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  498. return;
  499. }
  500. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  501. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  502. return;
  503. }
  504. var fragmentShaderUrl;
  505. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  506. fragmentShaderUrl = fragment;
  507. }
  508. else {
  509. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  510. }
  511. // Fragment shader
  512. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  513. };
  514. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  515. // Rebuild shaders source code
  516. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  517. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  518. vertexCode = prefix + vertexCode;
  519. fragmentCode = prefix + fragmentCode;
  520. // Number lines of shaders source code
  521. var i = 2;
  522. var regex = /\n/gm;
  523. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  524. i = 2;
  525. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  526. // Dump shaders name and formatted source code
  527. if (this.name.vertexElement) {
  528. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  529. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  530. }
  531. else if (this.name.vertex) {
  532. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  533. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  534. }
  535. else {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  538. }
  539. };
  540. ;
  541. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  542. var preparedSourceCode = this._processPrecision(sourceCode);
  543. if (this._engine.webGLVersion == 1) {
  544. callback(preparedSourceCode);
  545. return;
  546. }
  547. // Already converted
  548. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  549. callback(preparedSourceCode.replace("#version 300 es", ""));
  550. return;
  551. }
  552. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  553. // Remove extensions
  554. // #extension GL_OES_standard_derivatives : enable
  555. // #extension GL_EXT_shader_texture_lod : enable
  556. // #extension GL_EXT_frag_depth : enable
  557. // #extension GL_EXT_draw_buffers : require
  558. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  559. var result = preparedSourceCode.replace(regex, "");
  560. // Migrate to GLSL v300
  561. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  562. result = result.replace(/attribute[ \t]/g, "in ");
  563. result = result.replace(/[ \t]attribute/g, " in");
  564. if (isFragment) {
  565. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  566. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  567. result = result.replace(/texture2D\s*\(/g, "texture(");
  568. result = result.replace(/textureCube\s*\(/g, "texture(");
  569. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  570. result = result.replace(/gl_FragColor/g, "glFragColor");
  571. result = result.replace(/gl_FragData/g, "glFragData");
  572. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  573. }
  574. callback(result);
  575. };
  576. Effect.prototype._processIncludes = function (sourceCode, callback) {
  577. var _this = this;
  578. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  579. var match = regex.exec(sourceCode);
  580. var returnValue = new String(sourceCode);
  581. while (match != null) {
  582. var includeFile = match[1];
  583. // Uniform declaration
  584. if (includeFile.indexOf("__decl__") !== -1) {
  585. includeFile = includeFile.replace(/__decl__/, "");
  586. if (this._engine.supportsUniformBuffers) {
  587. includeFile = includeFile.replace(/Vertex/, "Ubo");
  588. includeFile = includeFile.replace(/Fragment/, "Ubo");
  589. }
  590. includeFile = includeFile + "Declaration";
  591. }
  592. if (Effect.IncludesShadersStore[includeFile]) {
  593. // Substitution
  594. var includeContent = Effect.IncludesShadersStore[includeFile];
  595. if (match[2]) {
  596. var splits = match[3].split(",");
  597. for (var index = 0; index < splits.length; index += 2) {
  598. var source = new RegExp(splits[index], "g");
  599. var dest = splits[index + 1];
  600. includeContent = includeContent.replace(source, dest);
  601. }
  602. }
  603. if (match[4]) {
  604. var indexString = match[5];
  605. if (indexString.indexOf("..") !== -1) {
  606. var indexSplits = indexString.split("..");
  607. var minIndex = parseInt(indexSplits[0]);
  608. var maxIndex = parseInt(indexSplits[1]);
  609. var sourceIncludeContent = includeContent.slice(0);
  610. includeContent = "";
  611. if (isNaN(maxIndex)) {
  612. maxIndex = this._indexParameters[indexSplits[1]];
  613. }
  614. for (var i = minIndex; i < maxIndex; i++) {
  615. if (!this._engine.supportsUniformBuffers) {
  616. // Ubo replacement
  617. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  618. return p1 + "{X}";
  619. });
  620. }
  621. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  622. }
  623. }
  624. else {
  625. if (!this._engine.supportsUniformBuffers) {
  626. // Ubo replacement
  627. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  628. return p1 + "{X}";
  629. });
  630. }
  631. includeContent = includeContent.replace(/\{X\}/g, indexString);
  632. }
  633. }
  634. // Replace
  635. returnValue = returnValue.replace(match[0], includeContent);
  636. }
  637. else {
  638. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  639. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  640. Effect.IncludesShadersStore[includeFile] = fileContent;
  641. _this._processIncludes(returnValue, callback);
  642. });
  643. return;
  644. }
  645. match = regex.exec(sourceCode);
  646. }
  647. callback(returnValue);
  648. };
  649. Effect.prototype._processPrecision = function (source) {
  650. if (source.indexOf("precision highp float") === -1) {
  651. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  652. source = "precision mediump float;\n" + source;
  653. }
  654. else {
  655. source = "precision highp float;\n" + source;
  656. }
  657. }
  658. else {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = source.replace("precision highp float", "precision mediump float");
  661. }
  662. }
  663. return source;
  664. };
  665. /**
  666. * Recompiles the webGL program
  667. * @param vertexSourceCode The source code for the vertex shader.
  668. * @param fragmentSourceCode The source code for the fragment shader.
  669. * @param onCompiled Callback called when completed.
  670. * @param onError Callback called on error.
  671. */
  672. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  673. var _this = this;
  674. this._isReady = false;
  675. this._vertexSourceCodeOverride = vertexSourceCode;
  676. this._fragmentSourceCodeOverride = fragmentSourceCode;
  677. this.onError = function (effect, error) {
  678. if (onError) {
  679. onError(error);
  680. }
  681. };
  682. this.onCompiled = function () {
  683. var scenes = _this.getEngine().scenes;
  684. for (var i = 0; i < scenes.length; i++) {
  685. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  686. }
  687. if (onCompiled) {
  688. onCompiled(_this._program);
  689. }
  690. };
  691. this._fallbacks = null;
  692. this._prepareEffect();
  693. };
  694. /**
  695. * Gets the uniform locations of the the specified variable names
  696. * @param names THe names of the variables to lookup.
  697. * @returns Array of locations in the same order as variable names.
  698. */
  699. Effect.prototype.getSpecificUniformLocations = function (names) {
  700. var engine = this._engine;
  701. return engine.getUniforms(this._program, names);
  702. };
  703. /**
  704. * Prepares the effect
  705. */
  706. Effect.prototype._prepareEffect = function () {
  707. var attributesNames = this._attributesNames;
  708. var defines = this.defines;
  709. var fallbacks = this._fallbacks;
  710. this._valueCache = {};
  711. var previousProgram = this._program;
  712. try {
  713. var engine = this._engine;
  714. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  715. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  716. }
  717. else {
  718. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  719. }
  720. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  721. if (engine.supportsUniformBuffers) {
  722. for (var name in this._uniformBuffersNames) {
  723. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  724. }
  725. }
  726. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  727. this._attributes = engine.getAttributes(this._program, attributesNames);
  728. var index;
  729. for (index = 0; index < this._samplers.length; index++) {
  730. var sampler = this.getUniform(this._samplers[index]);
  731. if (sampler == null) {
  732. this._samplers.splice(index, 1);
  733. index--;
  734. }
  735. }
  736. engine.bindSamplers(this);
  737. this._compilationError = "";
  738. this._isReady = true;
  739. if (this.onCompiled) {
  740. this.onCompiled(this);
  741. }
  742. this.onCompileObservable.notifyObservers(this);
  743. this.onCompileObservable.clear();
  744. // Unbind mesh reference in fallbacks
  745. if (this._fallbacks) {
  746. this._fallbacks.unBindMesh();
  747. }
  748. if (previousProgram) {
  749. this.getEngine()._deleteProgram(previousProgram);
  750. }
  751. }
  752. catch (e) {
  753. this._compilationError = e.message;
  754. // Let's go through fallbacks then
  755. BABYLON.Tools.Error("Unable to compile effect:");
  756. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  757. return " " + uniform;
  758. }));
  759. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  760. return " " + attribute;
  761. }));
  762. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  763. BABYLON.Tools.Error("Error: " + this._compilationError);
  764. if (previousProgram) {
  765. this._program = previousProgram;
  766. this._isReady = true;
  767. if (this.onError) {
  768. this.onError(this, this._compilationError);
  769. }
  770. this.onErrorObservable.notifyObservers(this);
  771. }
  772. if (fallbacks && fallbacks.isMoreFallbacks) {
  773. BABYLON.Tools.Error("Trying next fallback.");
  774. this.defines = fallbacks.reduce(this.defines, this);
  775. this._prepareEffect();
  776. }
  777. else {
  778. if (this.onError) {
  779. this.onError(this, this._compilationError);
  780. }
  781. this.onErrorObservable.notifyObservers(this);
  782. this.onErrorObservable.clear();
  783. // Unbind mesh reference in fallbacks
  784. if (this._fallbacks) {
  785. this._fallbacks.unBindMesh();
  786. }
  787. }
  788. }
  789. };
  790. Object.defineProperty(Effect.prototype, "isSupported", {
  791. /**
  792. * Checks if the effect is supported. (Must be called after compilation)
  793. */
  794. get: function () {
  795. return this._compilationError === "";
  796. },
  797. enumerable: true,
  798. configurable: true
  799. });
  800. /**
  801. * Binds a texture to the engine to be used as output of the shader.
  802. * @param channel Name of the output variable.
  803. * @param texture Texture to bind.
  804. */
  805. Effect.prototype._bindTexture = function (channel, texture) {
  806. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  807. };
  808. /**
  809. * Sets a texture on the engine to be used in the shader.
  810. * @param channel Name of the sampler variable.
  811. * @param texture Texture to set.
  812. */
  813. Effect.prototype.setTexture = function (channel, texture) {
  814. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  815. };
  816. /**
  817. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  822. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets an array of textures on the engine to be used in the shader.
  826. * @param channel Name of the variable.
  827. * @param textures Textures to set.
  828. */
  829. Effect.prototype.setTextureArray = function (channel, textures) {
  830. if (this._samplers.indexOf(channel + "Ex") === -1) {
  831. var initialPos = this._samplers.indexOf(channel);
  832. for (var index = 1; index < textures.length; index++) {
  833. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  834. }
  835. }
  836. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  837. };
  838. /**
  839. * 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)
  840. * @param channel Name of the sampler variable.
  841. * @param postProcess Post process to get the input texture from.
  842. */
  843. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  844. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  845. };
  846. /**
  847. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  848. * 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)
  849. * @param channel Name of the sampler variable.
  850. * @param postProcess Post process to get the output texture from.
  851. */
  852. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  853. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  854. };
  855. /** @ignore */
  856. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  857. var cache = this._valueCache[uniformName];
  858. var flag = matrix.updateFlag;
  859. if (cache !== undefined && cache === flag) {
  860. return false;
  861. }
  862. this._valueCache[uniformName] = flag;
  863. return true;
  864. };
  865. /** @ignore */
  866. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  867. var cache = this._valueCache[uniformName];
  868. if (!cache) {
  869. cache = [x, y];
  870. this._valueCache[uniformName] = cache;
  871. return true;
  872. }
  873. var changed = false;
  874. if (cache[0] !== x) {
  875. cache[0] = x;
  876. changed = true;
  877. }
  878. if (cache[1] !== y) {
  879. cache[1] = y;
  880. changed = true;
  881. }
  882. return changed;
  883. };
  884. /** @ignore */
  885. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  886. var cache = this._valueCache[uniformName];
  887. if (!cache) {
  888. cache = [x, y, z];
  889. this._valueCache[uniformName] = cache;
  890. return true;
  891. }
  892. var changed = false;
  893. if (cache[0] !== x) {
  894. cache[0] = x;
  895. changed = true;
  896. }
  897. if (cache[1] !== y) {
  898. cache[1] = y;
  899. changed = true;
  900. }
  901. if (cache[2] !== z) {
  902. cache[2] = z;
  903. changed = true;
  904. }
  905. return changed;
  906. };
  907. /** @ignore */
  908. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  909. var cache = this._valueCache[uniformName];
  910. if (!cache) {
  911. cache = [x, y, z, w];
  912. this._valueCache[uniformName] = cache;
  913. return true;
  914. }
  915. var changed = false;
  916. if (cache[0] !== x) {
  917. cache[0] = x;
  918. changed = true;
  919. }
  920. if (cache[1] !== y) {
  921. cache[1] = y;
  922. changed = true;
  923. }
  924. if (cache[2] !== z) {
  925. cache[2] = z;
  926. changed = true;
  927. }
  928. if (cache[3] !== w) {
  929. cache[3] = w;
  930. changed = true;
  931. }
  932. return changed;
  933. };
  934. /**
  935. * Binds a buffer to a uniform.
  936. * @param buffer Buffer to bind.
  937. * @param name Name of the uniform variable to bind to.
  938. */
  939. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  940. var bufferName = this._uniformBuffersNames[name];
  941. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  942. return;
  943. }
  944. Effect._baseCache[bufferName] = buffer;
  945. this._engine.bindUniformBufferBase(buffer, bufferName);
  946. };
  947. /**
  948. * Binds block to a uniform.
  949. * @param blockName Name of the block to bind.
  950. * @param index Index to bind.
  951. */
  952. Effect.prototype.bindUniformBlock = function (blockName, index) {
  953. this._engine.bindUniformBlock(this._program, blockName, index);
  954. };
  955. /**
  956. * Sets an interger value on a uniform variable.
  957. * @param uniformName Name of the variable.
  958. * @param value Value to be set.
  959. * @returns this effect.
  960. */
  961. Effect.prototype.setInt = function (uniformName, value) {
  962. var cache = this._valueCache[uniformName];
  963. if (cache !== undefined && cache === value)
  964. return this;
  965. this._valueCache[uniformName] = value;
  966. this._engine.setInt(this.getUniform(uniformName), value);
  967. return this;
  968. };
  969. /**
  970. * Sets an int array on a uniform variable.
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setIntArray = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setIntArray(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * 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)
  982. * @param uniformName Name of the variable.
  983. * @param array array to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setIntArray2 = function (uniformName, array) {
  987. this._valueCache[uniformName] = null;
  988. this._engine.setIntArray2(this.getUniform(uniformName), array);
  989. return this;
  990. };
  991. /**
  992. * 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)
  993. * @param uniformName Name of the variable.
  994. * @param array array to be set.
  995. * @returns this effect.
  996. */
  997. Effect.prototype.setIntArray3 = function (uniformName, array) {
  998. this._valueCache[uniformName] = null;
  999. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1000. return this;
  1001. };
  1002. /**
  1003. * 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)
  1004. * @param uniformName Name of the variable.
  1005. * @param array array to be set.
  1006. * @returns this effect.
  1007. */
  1008. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1009. this._valueCache[uniformName] = null;
  1010. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1011. return this;
  1012. };
  1013. /**
  1014. * Sets an float array on a uniform variable.
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setFloatArray = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param array array to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1033. return this;
  1034. };
  1035. /**
  1036. * 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)
  1037. * @param uniformName Name of the variable.
  1038. * @param array array to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1044. return this;
  1045. };
  1046. /**
  1047. * 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)
  1048. * @param uniformName Name of the variable.
  1049. * @param array array to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1053. this._valueCache[uniformName] = null;
  1054. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1055. return this;
  1056. };
  1057. /**
  1058. * Sets an array on a uniform variable.
  1059. * @param uniformName Name of the variable.
  1060. * @param array array to be set.
  1061. * @returns this effect.
  1062. */
  1063. Effect.prototype.setArray = function (uniformName, array) {
  1064. this._valueCache[uniformName] = null;
  1065. this._engine.setArray(this.getUniform(uniformName), array);
  1066. return this;
  1067. };
  1068. /**
  1069. * 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)
  1070. * @param uniformName Name of the variable.
  1071. * @param array array to be set.
  1072. * @returns this effect.
  1073. */
  1074. Effect.prototype.setArray2 = function (uniformName, array) {
  1075. this._valueCache[uniformName] = null;
  1076. this._engine.setArray2(this.getUniform(uniformName), array);
  1077. return this;
  1078. };
  1079. /**
  1080. * 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)
  1081. * @param uniformName Name of the variable.
  1082. * @param array array to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setArray3 = function (uniformName, array) {
  1086. this._valueCache[uniformName] = null;
  1087. this._engine.setArray3(this.getUniform(uniformName), array);
  1088. return this;
  1089. };
  1090. /**
  1091. * 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)
  1092. * @param uniformName Name of the variable.
  1093. * @param array array to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setArray4 = function (uniformName, array) {
  1097. this._valueCache[uniformName] = null;
  1098. this._engine.setArray4(this.getUniform(uniformName), array);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets matrices on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param matrices matrices to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1108. if (!matrices) {
  1109. return this;
  1110. }
  1111. this._valueCache[uniformName] = null;
  1112. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets matrix on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param matrix matrix to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1122. if (this._cacheMatrix(uniformName, matrix)) {
  1123. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * 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)
  1129. * @param uniformName Name of the variable.
  1130. * @param matrix matrix to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1134. this._valueCache[uniformName] = null;
  1135. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1136. return this;
  1137. };
  1138. /**
  1139. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1140. * @param uniformName Name of the variable.
  1141. * @param matrix matrix to be set.
  1142. * @returns this effect.
  1143. */
  1144. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1145. this._valueCache[uniformName] = null;
  1146. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets a float on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param value value to be set.
  1153. * @returns this effect.
  1154. */
  1155. Effect.prototype.setFloat = function (uniformName, value) {
  1156. var cache = this._valueCache[uniformName];
  1157. if (cache !== undefined && cache === value)
  1158. return this;
  1159. this._valueCache[uniformName] = value;
  1160. this._engine.setFloat(this.getUniform(uniformName), value);
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a boolean on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param bool value to be set.
  1167. * @returns this effect.
  1168. */
  1169. Effect.prototype.setBool = function (uniformName, bool) {
  1170. var cache = this._valueCache[uniformName];
  1171. if (cache !== undefined && cache === bool)
  1172. return this;
  1173. this._valueCache[uniformName] = bool;
  1174. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Vector2 on a uniform variable.
  1179. * @param uniformName Name of the variable.
  1180. * @param vector2 vector2 to be set.
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1184. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1185. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Sets a float2 on a uniform variable.
  1191. * @param uniformName Name of the variable.
  1192. * @param x First float in float2.
  1193. * @param y Second float in float2.
  1194. * @returns this effect.
  1195. */
  1196. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1197. if (this._cacheFloat2(uniformName, x, y)) {
  1198. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1199. }
  1200. return this;
  1201. };
  1202. /**
  1203. * Sets a Vector3 on a uniform variable.
  1204. * @param uniformName Name of the variable.
  1205. * @param vector3 Value to be set.
  1206. * @returns this effect.
  1207. */
  1208. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1209. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1210. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1211. }
  1212. return this;
  1213. };
  1214. /**
  1215. * Sets a float3 on a uniform variable.
  1216. * @param uniformName Name of the variable.
  1217. * @param x First float in float3.
  1218. * @param y Second float in float3.
  1219. * @param z Third float in float3.
  1220. * @returns this effect.
  1221. */
  1222. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1223. if (this._cacheFloat3(uniformName, x, y, z)) {
  1224. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1225. }
  1226. return this;
  1227. };
  1228. /**
  1229. * Sets a Vector4 on a uniform variable.
  1230. * @param uniformName Name of the variable.
  1231. * @param vector4 Value to be set.
  1232. * @returns this effect.
  1233. */
  1234. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1235. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1236. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1237. }
  1238. return this;
  1239. };
  1240. /**
  1241. * Sets a float4 on a uniform variable.
  1242. * @param uniformName Name of the variable.
  1243. * @param x First float in float4.
  1244. * @param y Second float in float4.
  1245. * @param z Third float in float4.
  1246. * @param w Fourth float in float4.
  1247. * @returns this effect.
  1248. */
  1249. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1250. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1251. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1252. }
  1253. return this;
  1254. };
  1255. /**
  1256. * Sets a Color3 on a uniform variable.
  1257. * @param uniformName Name of the variable.
  1258. * @param color3 Value to be set.
  1259. * @returns this effect.
  1260. */
  1261. Effect.prototype.setColor3 = function (uniformName, color3) {
  1262. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1263. this._engine.setColor3(this.getUniform(uniformName), color3);
  1264. }
  1265. return this;
  1266. };
  1267. /**
  1268. * Sets a Color4 on a uniform variable.
  1269. * @param uniformName Name of the variable.
  1270. * @param color3 Value to be set.
  1271. * @param alpha Alpha value to be set.
  1272. * @returns this effect.
  1273. */
  1274. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1275. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1276. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1277. }
  1278. return this;
  1279. };
  1280. /**
  1281. * Sets a Color4 on a uniform variable
  1282. * @param uniformName defines the name of the variable
  1283. * @param color4 defines the value to be set
  1284. * @returns this effect.
  1285. */
  1286. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1287. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1288. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1289. }
  1290. return this;
  1291. };
  1292. /**
  1293. * Resets the cache of effects.
  1294. */
  1295. Effect.ResetCache = function () {
  1296. Effect._baseCache = {};
  1297. };
  1298. Effect._uniqueIdSeed = 0;
  1299. Effect._baseCache = {};
  1300. /**
  1301. * Store of each shader (The can be looked up using effect.key)
  1302. */
  1303. Effect.ShadersStore = {};
  1304. /**
  1305. * Store of each included file for a shader (The can be looked up using effect.key)
  1306. */
  1307. Effect.IncludesShadersStore = {};
  1308. return Effect;
  1309. }());
  1310. BABYLON.Effect = Effect;
  1311. })(BABYLON || (BABYLON = {}));
  1312. //# sourceMappingURL=babylon.effect.js.map
  1313. "use strict";
  1314. //# sourceMappingURL=babylon.types.js.map
  1315. "use strict";
  1316. var BABYLON;
  1317. (function (BABYLON) {
  1318. var KeyboardEventTypes = /** @class */ (function () {
  1319. function KeyboardEventTypes() {
  1320. }
  1321. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1322. get: function () {
  1323. return KeyboardEventTypes._KEYDOWN;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1329. get: function () {
  1330. return KeyboardEventTypes._KEYUP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. KeyboardEventTypes._KEYDOWN = 0x01;
  1336. KeyboardEventTypes._KEYUP = 0x02;
  1337. return KeyboardEventTypes;
  1338. }());
  1339. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1340. var KeyboardInfo = /** @class */ (function () {
  1341. function KeyboardInfo(type, event) {
  1342. this.type = type;
  1343. this.event = event;
  1344. }
  1345. return KeyboardInfo;
  1346. }());
  1347. BABYLON.KeyboardInfo = KeyboardInfo;
  1348. /**
  1349. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1350. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1351. */
  1352. var KeyboardInfoPre = /** @class */ (function (_super) {
  1353. __extends(KeyboardInfoPre, _super);
  1354. function KeyboardInfoPre(type, event) {
  1355. var _this = _super.call(this, type, event) || this;
  1356. _this.skipOnPointerObservable = false;
  1357. return _this;
  1358. }
  1359. return KeyboardInfoPre;
  1360. }(KeyboardInfo));
  1361. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1362. })(BABYLON || (BABYLON = {}));
  1363. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1364. "use strict";
  1365. var BABYLON;
  1366. (function (BABYLON) {
  1367. var PointerEventTypes = /** @class */ (function () {
  1368. function PointerEventTypes() {
  1369. }
  1370. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1371. get: function () {
  1372. return PointerEventTypes._POINTERDOWN;
  1373. },
  1374. enumerable: true,
  1375. configurable: true
  1376. });
  1377. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1378. get: function () {
  1379. return PointerEventTypes._POINTERUP;
  1380. },
  1381. enumerable: true,
  1382. configurable: true
  1383. });
  1384. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1385. get: function () {
  1386. return PointerEventTypes._POINTERMOVE;
  1387. },
  1388. enumerable: true,
  1389. configurable: true
  1390. });
  1391. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1392. get: function () {
  1393. return PointerEventTypes._POINTERWHEEL;
  1394. },
  1395. enumerable: true,
  1396. configurable: true
  1397. });
  1398. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1399. get: function () {
  1400. return PointerEventTypes._POINTERPICK;
  1401. },
  1402. enumerable: true,
  1403. configurable: true
  1404. });
  1405. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1406. get: function () {
  1407. return PointerEventTypes._POINTERTAP;
  1408. },
  1409. enumerable: true,
  1410. configurable: true
  1411. });
  1412. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1413. get: function () {
  1414. return PointerEventTypes._POINTERDOUBLETAP;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. PointerEventTypes._POINTERDOWN = 0x01;
  1420. PointerEventTypes._POINTERUP = 0x02;
  1421. PointerEventTypes._POINTERMOVE = 0x04;
  1422. PointerEventTypes._POINTERWHEEL = 0x08;
  1423. PointerEventTypes._POINTERPICK = 0x10;
  1424. PointerEventTypes._POINTERTAP = 0x20;
  1425. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1426. return PointerEventTypes;
  1427. }());
  1428. BABYLON.PointerEventTypes = PointerEventTypes;
  1429. var PointerInfoBase = /** @class */ (function () {
  1430. function PointerInfoBase(type, event) {
  1431. this.type = type;
  1432. this.event = event;
  1433. }
  1434. return PointerInfoBase;
  1435. }());
  1436. BABYLON.PointerInfoBase = PointerInfoBase;
  1437. /**
  1438. * This class is used to store pointer related info for the onPrePointerObservable event.
  1439. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1440. */
  1441. var PointerInfoPre = /** @class */ (function (_super) {
  1442. __extends(PointerInfoPre, _super);
  1443. function PointerInfoPre(type, event, localX, localY) {
  1444. var _this = _super.call(this, type, event) || this;
  1445. _this.skipOnPointerObservable = false;
  1446. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1447. return _this;
  1448. }
  1449. return PointerInfoPre;
  1450. }(PointerInfoBase));
  1451. BABYLON.PointerInfoPre = PointerInfoPre;
  1452. /**
  1453. * This type contains all the data related to a pointer event in Babylon.js.
  1454. * 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.
  1455. */
  1456. var PointerInfo = /** @class */ (function (_super) {
  1457. __extends(PointerInfo, _super);
  1458. function PointerInfo(type, event, pickInfo) {
  1459. var _this = _super.call(this, type, event) || this;
  1460. _this.pickInfo = pickInfo;
  1461. return _this;
  1462. }
  1463. return PointerInfo;
  1464. }(PointerInfoBase));
  1465. BABYLON.PointerInfo = PointerInfo;
  1466. })(BABYLON || (BABYLON = {}));
  1467. //# sourceMappingURL=babylon.pointerEvents.js.map
  1468. "use strict";
  1469. var BABYLON;
  1470. (function (BABYLON) {
  1471. BABYLON.ToGammaSpace = 1 / 2.2;
  1472. BABYLON.ToLinearSpace = 2.2;
  1473. BABYLON.Epsilon = 0.001;
  1474. /**
  1475. * Class used to hold a RBG color
  1476. */
  1477. var Color3 = /** @class */ (function () {
  1478. /**
  1479. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1480. * @param r defines the red component (between 0 and 1, default is 0)
  1481. * @param g defines the green component (between 0 and 1, default is 0)
  1482. * @param b defines the blue component (between 0 and 1, default is 0)
  1483. */
  1484. function Color3(
  1485. /**
  1486. * Defines the red component (between 0 and 1, default is 0)
  1487. */
  1488. r,
  1489. /**
  1490. * Defines the green component (between 0 and 1, default is 0)
  1491. */
  1492. g,
  1493. /**
  1494. * Defines the blue component (between 0 and 1, default is 0)
  1495. */
  1496. b) {
  1497. if (r === void 0) { r = 0; }
  1498. if (g === void 0) { g = 0; }
  1499. if (b === void 0) { b = 0; }
  1500. this.r = r;
  1501. this.g = g;
  1502. this.b = b;
  1503. }
  1504. /**
  1505. * Creates a string with the Color3 current values
  1506. * @returns the string representation of the Color3 object
  1507. */
  1508. Color3.prototype.toString = function () {
  1509. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1510. };
  1511. /**
  1512. * Returns the string "Color3"
  1513. * @returns "Color3"
  1514. */
  1515. Color3.prototype.getClassName = function () {
  1516. return "Color3";
  1517. };
  1518. /**
  1519. * Compute the Color3 hash code
  1520. * @returns an unique number that can be used to hash Color3 objects
  1521. */
  1522. Color3.prototype.getHashCode = function () {
  1523. var hash = this.r || 0;
  1524. hash = (hash * 397) ^ (this.g || 0);
  1525. hash = (hash * 397) ^ (this.b || 0);
  1526. return hash;
  1527. };
  1528. // Operators
  1529. /**
  1530. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1531. * @param array defines the array where to store the r,g,b components
  1532. * @param index defines an optional index in the target array to define where to start storing values
  1533. * @returns the current Color3 object
  1534. */
  1535. Color3.prototype.toArray = function (array, index) {
  1536. if (index === undefined) {
  1537. index = 0;
  1538. }
  1539. array[index] = this.r;
  1540. array[index + 1] = this.g;
  1541. array[index + 2] = this.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1546. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1547. * @returns a new {BABYLON.Color4} object
  1548. */
  1549. Color3.prototype.toColor4 = function (alpha) {
  1550. if (alpha === void 0) { alpha = 1; }
  1551. return new Color4(this.r, this.g, this.b, alpha);
  1552. };
  1553. /**
  1554. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1555. * @returns the new array
  1556. */
  1557. Color3.prototype.asArray = function () {
  1558. var result = new Array();
  1559. this.toArray(result, 0);
  1560. return result;
  1561. };
  1562. /**
  1563. * Returns the luminance value
  1564. * @returns a float value
  1565. */
  1566. Color3.prototype.toLuminance = function () {
  1567. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1568. };
  1569. /**
  1570. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3 object
  1573. */
  1574. Color3.prototype.multiply = function (otherColor) {
  1575. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1576. };
  1577. /**
  1578. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines the Color3 object where to store the result
  1581. * @returns the current Color3
  1582. */
  1583. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1584. result.r = this.r * otherColor.r;
  1585. result.g = this.g * otherColor.g;
  1586. result.b = this.b * otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Determines equality between Color3 objects
  1591. * @param otherColor defines the second operand
  1592. * @returns true if the rgb values are equal to the passed ones
  1593. */
  1594. Color3.prototype.equals = function (otherColor) {
  1595. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1596. };
  1597. /**
  1598. * Determines equality between the current Color3 object and a set of r,b,g values
  1599. * @param r defines the red component to check
  1600. * @param g defines the green component to check
  1601. * @param b defines the blue component to check
  1602. * @returns true if the rgb values are equal to the passed ones
  1603. */
  1604. Color3.prototype.equalsFloats = function (r, g, b) {
  1605. return this.r === r && this.g === g && this.b === b;
  1606. };
  1607. /**
  1608. * Multiplies in place each rgb value by scale
  1609. * @param scale defines the scaling factor
  1610. * @returns the updated Color3
  1611. */
  1612. Color3.prototype.scale = function (scale) {
  1613. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1614. };
  1615. /**
  1616. * Multiplies the rgb values by scale and stores the result into "result"
  1617. * @param scale defines the scaling factor
  1618. * @param result defines the Color3 object where to store the result
  1619. * @returns the unmodified current Color3
  1620. */
  1621. Color3.prototype.scaleToRef = function (scale, result) {
  1622. result.r = this.r * scale;
  1623. result.g = this.g * scale;
  1624. result.b = this.b * scale;
  1625. return this;
  1626. };
  1627. /**
  1628. * Scale the current Color3 values by a factor and add the result to a given Color3
  1629. * @param scale defines the scale factor
  1630. * @param result defines color to store the result into
  1631. * @returns the unmodified current Color3
  1632. */
  1633. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1634. result.r += this.r * scale;
  1635. result.g += this.g * scale;
  1636. result.b += this.b * scale;
  1637. return this;
  1638. };
  1639. /**
  1640. * Clamps the rgb values by the min and max values and stores the result into "result"
  1641. * @param min defines minimum clamping value (default is 0)
  1642. * @param max defines maximum clamping value (default is 1)
  1643. * @param result defines color to store the result into
  1644. * @returns the original Color3
  1645. */
  1646. Color3.prototype.clampToRef = function (min, max, result) {
  1647. if (min === void 0) { min = 0; }
  1648. if (max === void 0) { max = 1; }
  1649. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1650. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1651. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1652. return this;
  1653. };
  1654. /**
  1655. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1656. * @param otherColor defines the second operand
  1657. * @returns the new Color3
  1658. */
  1659. Color3.prototype.add = function (otherColor) {
  1660. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1661. };
  1662. /**
  1663. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1664. * @param otherColor defines the second operand
  1665. * @param result defines Color3 object to store the result into
  1666. * @returns the unmodified current Color3
  1667. */
  1668. Color3.prototype.addToRef = function (otherColor, result) {
  1669. result.r = this.r + otherColor.r;
  1670. result.g = this.g + otherColor.g;
  1671. result.b = this.b + otherColor.b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1676. * @param otherColor defines the second operand
  1677. * @returns the new Color3
  1678. */
  1679. Color3.prototype.subtract = function (otherColor) {
  1680. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1681. };
  1682. /**
  1683. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1684. * @param otherColor defines the second operand
  1685. * @param result defines Color3 object to store the result into
  1686. * @returns the unmodified current Color3
  1687. */
  1688. Color3.prototype.subtractToRef = function (otherColor, result) {
  1689. result.r = this.r - otherColor.r;
  1690. result.g = this.g - otherColor.g;
  1691. result.b = this.b - otherColor.b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Copy the current object
  1696. * @returns a new Color3 copied the current one
  1697. */
  1698. Color3.prototype.clone = function () {
  1699. return new Color3(this.r, this.g, this.b);
  1700. };
  1701. /**
  1702. * Copies the rgb values from the source in the current Color3
  1703. * @param source defines the source Color3 object
  1704. * @returns the updated Color3 object
  1705. */
  1706. Color3.prototype.copyFrom = function (source) {
  1707. this.r = source.r;
  1708. this.g = source.g;
  1709. this.b = source.b;
  1710. return this;
  1711. };
  1712. /**
  1713. * Updates the Color3 rgb values from the passed floats
  1714. * @param r defines the red component to read from
  1715. * @param g defines the green component to read from
  1716. * @param b defines the blue component to read from
  1717. * @returns the current Color3 object
  1718. */
  1719. Color3.prototype.copyFromFloats = function (r, g, b) {
  1720. this.r = r;
  1721. this.g = g;
  1722. this.b = b;
  1723. return this;
  1724. };
  1725. /**
  1726. * Updates the Color3 rgb values from the passed floats
  1727. * @param r defines the red component to read from
  1728. * @param g defines the green component to read from
  1729. * @param b defines the blue component to read from
  1730. * @returns the current Color3 object
  1731. */
  1732. Color3.prototype.set = function (r, g, b) {
  1733. return this.copyFromFloats(r, g, b);
  1734. };
  1735. /**
  1736. * Compute the Color3 hexadecimal code as a string
  1737. * @returns a string containing the hexadecimal representation of the Color3 object
  1738. */
  1739. Color3.prototype.toHexString = function () {
  1740. var intR = (this.r * 255) | 0;
  1741. var intG = (this.g * 255) | 0;
  1742. var intB = (this.b * 255) | 0;
  1743. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1744. };
  1745. /**
  1746. * Computes a new Color3 converted from the current one to linear space
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.prototype.toLinearSpace = function () {
  1750. var convertedColor = new Color3();
  1751. this.toLinearSpaceToRef(convertedColor);
  1752. return convertedColor;
  1753. };
  1754. /**
  1755. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1756. * @param convertedColor defines the Color3 object where to store the linear space version
  1757. * @returns the unmodified Color3
  1758. */
  1759. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1760. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1761. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1762. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1763. return this;
  1764. };
  1765. /**
  1766. * Computes a new Color3 converted from the current one to gamma space
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.prototype.toGammaSpace = function () {
  1770. var convertedColor = new Color3();
  1771. this.toGammaSpaceToRef(convertedColor);
  1772. return convertedColor;
  1773. };
  1774. /**
  1775. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1776. * @param convertedColor defines the Color3 object where to store the gamma space version
  1777. * @returns the unmodified Color3
  1778. */
  1779. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1780. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1781. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1782. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1783. return this;
  1784. };
  1785. // Statics
  1786. /**
  1787. * Creates a new Color3 from the string containing valid hexadecimal values
  1788. * @param hex defines a string containing valid hexadecimal values
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.FromHexString = function (hex) {
  1792. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1793. return new Color3(0, 0, 0);
  1794. }
  1795. var r = parseInt(hex.substring(1, 3), 16);
  1796. var g = parseInt(hex.substring(3, 5), 16);
  1797. var b = parseInt(hex.substring(5, 7), 16);
  1798. return Color3.FromInts(r, g, b);
  1799. };
  1800. /**
  1801. * Creates a new Vector3 from the starting index of the passed array
  1802. * @param array defines the source array
  1803. * @param offset defines an offset in the source array
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1809. };
  1810. /**
  1811. * Creates a new Color3 from integer values (< 256)
  1812. * @param r defines the red component to read from (value between 0 and 255)
  1813. * @param g defines the green component to read from (value between 0 and 255)
  1814. * @param b defines the blue component to read from (value between 0 and 255)
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.FromInts = function (r, g, b) {
  1818. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1819. };
  1820. /**
  1821. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1822. * @param start defines the start Color3 value
  1823. * @param end defines the end Color3 value
  1824. * @param amount defines the gradient value between start and end
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Lerp = function (start, end, amount) {
  1828. var r = start.r + ((end.r - start.r) * amount);
  1829. var g = start.g + ((end.g - start.g) * amount);
  1830. var b = start.b + ((end.b - start.b) * amount);
  1831. return new Color3(r, g, b);
  1832. };
  1833. /**
  1834. * Returns a Color3 value containing a red color
  1835. * @returns a new Color3 object
  1836. */
  1837. Color3.Red = function () { return new Color3(1, 0, 0); };
  1838. /**
  1839. * Returns a Color3 value containing a green color
  1840. * @returns a new Color3 object
  1841. */
  1842. Color3.Green = function () { return new Color3(0, 1, 0); };
  1843. /**
  1844. * Returns a Color3 value containing a blue color
  1845. * @returns a new Color3 object
  1846. */
  1847. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1848. /**
  1849. * Returns a Color3 value containing a black color
  1850. * @returns a new Color3 object
  1851. */
  1852. Color3.Black = function () { return new Color3(0, 0, 0); };
  1853. /**
  1854. * Returns a Color3 value containing a white color
  1855. * @returns a new Color3 object
  1856. */
  1857. Color3.White = function () { return new Color3(1, 1, 1); };
  1858. /**
  1859. * Returns a Color3 value containing a purple color
  1860. * @returns a new Color3 object
  1861. */
  1862. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1863. /**
  1864. * Returns a Color3 value containing a magenta color
  1865. * @returns a new Color3 object
  1866. */
  1867. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1868. /**
  1869. * Returns a Color3 value containing a yellow color
  1870. * @returns a new Color3 object
  1871. */
  1872. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1873. /**
  1874. * Returns a Color3 value containing a gray color
  1875. * @returns a new Color3 object
  1876. */
  1877. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1878. /**
  1879. * Returns a Color3 value containing a teal color
  1880. * @returns a new Color3 object
  1881. */
  1882. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1883. /**
  1884. * Returns a Color3 value containing a random color
  1885. * @returns a new Color3 object
  1886. */
  1887. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1888. return Color3;
  1889. }());
  1890. BABYLON.Color3 = Color3;
  1891. /**
  1892. * Class used to hold a RBGA color
  1893. */
  1894. var Color4 = /** @class */ (function () {
  1895. /**
  1896. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1897. * @param r defines the red component (between 0 and 1, default is 0)
  1898. * @param g defines the green component (between 0 and 1, default is 0)
  1899. * @param b defines the blue component (between 0 and 1, default is 0)
  1900. * @param a defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. function Color4(
  1903. /**
  1904. * Defines the red component (between 0 and 1, default is 0)
  1905. */
  1906. r,
  1907. /**
  1908. * Defines the green component (between 0 and 1, default is 0)
  1909. */
  1910. g,
  1911. /**
  1912. * Defines the blue component (between 0 and 1, default is 0)
  1913. */
  1914. b,
  1915. /**
  1916. * Defines the alpha component (between 0 and 1, default is 1)
  1917. */
  1918. a) {
  1919. if (r === void 0) { r = 0; }
  1920. if (g === void 0) { g = 0; }
  1921. if (b === void 0) { b = 0; }
  1922. if (a === void 0) { a = 1; }
  1923. this.r = r;
  1924. this.g = g;
  1925. this.b = b;
  1926. this.a = a;
  1927. }
  1928. // Operators
  1929. /**
  1930. * Adds in place the passed Color4 values to the current Color4 object
  1931. * @param right defines the second operand
  1932. * @returns the current updated Color4 object
  1933. */
  1934. Color4.prototype.addInPlace = function (right) {
  1935. this.r += right.r;
  1936. this.g += right.g;
  1937. this.b += right.b;
  1938. this.a += right.a;
  1939. return this;
  1940. };
  1941. /**
  1942. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1943. * @returns the new array
  1944. */
  1945. Color4.prototype.asArray = function () {
  1946. var result = new Array();
  1947. this.toArray(result, 0);
  1948. return result;
  1949. };
  1950. /**
  1951. * Stores from the starting index in the passed array the Color4 successive values
  1952. * @param array defines the array where to store the r,g,b components
  1953. * @param index defines an optional index in the target array to define where to start storing values
  1954. * @returns the current Color4 object
  1955. */
  1956. Color4.prototype.toArray = function (array, index) {
  1957. if (index === undefined) {
  1958. index = 0;
  1959. }
  1960. array[index] = this.r;
  1961. array[index + 1] = this.g;
  1962. array[index + 2] = this.b;
  1963. array[index + 3] = this.a;
  1964. return this;
  1965. };
  1966. /**
  1967. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1968. * @param right defines the second operand
  1969. * @returns a new Color4 object
  1970. */
  1971. Color4.prototype.add = function (right) {
  1972. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.subtract = function (right) {
  1980. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1981. };
  1982. /**
  1983. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1984. * @param right defines the second operand
  1985. * @param result defines the Color4 object where to store the result
  1986. * @returns the current Color4 object
  1987. */
  1988. Color4.prototype.subtractToRef = function (right, result) {
  1989. result.r = this.r - right.r;
  1990. result.g = this.g - right.g;
  1991. result.b = this.b - right.b;
  1992. result.a = this.a - right.a;
  1993. return this;
  1994. };
  1995. /**
  1996. * Creates a new Color4 with the current Color4 values multiplied by scale
  1997. * @param scale defines the scaling factor to apply
  1998. * @returns a new Color4 object
  1999. */
  2000. Color4.prototype.scale = function (scale) {
  2001. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2002. };
  2003. /**
  2004. * Multiplies the current Color4 values by scale and stores the result in "result"
  2005. * @param scale defines the scaling factor to apply
  2006. * @param result defines the Color4 object where to store the result
  2007. * @returns the current unmodified Color4
  2008. */
  2009. Color4.prototype.scaleToRef = function (scale, result) {
  2010. result.r = this.r * scale;
  2011. result.g = this.g * scale;
  2012. result.b = this.b * scale;
  2013. result.a = this.a * scale;
  2014. return this;
  2015. };
  2016. /**
  2017. * Scale the current Color4 values by a factor and add the result to a given Color4
  2018. * @param scale defines the scale factor
  2019. * @param result defines the Color4 object where to store the result
  2020. * @returns the unmodified current Color4
  2021. */
  2022. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2023. result.r += this.r * scale;
  2024. result.g += this.g * scale;
  2025. result.b += this.b * scale;
  2026. result.a += this.a * scale;
  2027. return this;
  2028. };
  2029. /**
  2030. * Clamps the rgb values by the min and max values and stores the result into "result"
  2031. * @param min defines minimum clamping value (default is 0)
  2032. * @param max defines maximum clamping value (default is 1)
  2033. * @param result defines color to store the result into.
  2034. * @returns the cuurent Color4
  2035. */
  2036. Color4.prototype.clampToRef = function (min, max, result) {
  2037. if (min === void 0) { min = 0; }
  2038. if (max === void 0) { max = 1; }
  2039. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2040. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2041. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2042. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2043. return this;
  2044. };
  2045. /**
  2046. * Multipy an Color4 value by another and return a new Color4 object
  2047. * @param color defines the Color4 value to multiply by
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.multiply = function (color) {
  2051. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2052. };
  2053. /**
  2054. * Multipy a Color4 value by another and push the result in a reference value
  2055. * @param color defines the Color4 value to multiply by
  2056. * @param result defines the Color4 to fill the result in
  2057. * @returns the result Color4
  2058. */
  2059. Color4.prototype.multiplyToRef = function (color, result) {
  2060. result.r = this.r * color.r;
  2061. result.g = this.g * color.g;
  2062. result.b = this.b * color.b;
  2063. result.a = this.a * color.a;
  2064. return result;
  2065. };
  2066. /**
  2067. * Creates a string with the Color4 current values
  2068. * @returns the string representation of the Color4 object
  2069. */
  2070. Color4.prototype.toString = function () {
  2071. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2072. };
  2073. /**
  2074. * Returns the string "Color4"
  2075. * @returns "Color4"
  2076. */
  2077. Color4.prototype.getClassName = function () {
  2078. return "Color4";
  2079. };
  2080. /**
  2081. * Compute the Color4 hash code
  2082. * @returns an unique number that can be used to hash Color4 objects
  2083. */
  2084. Color4.prototype.getHashCode = function () {
  2085. var hash = this.r || 0;
  2086. hash = (hash * 397) ^ (this.g || 0);
  2087. hash = (hash * 397) ^ (this.b || 0);
  2088. hash = (hash * 397) ^ (this.a || 0);
  2089. return hash;
  2090. };
  2091. /**
  2092. * Creates a new Color4 copied from the current one
  2093. * @returns a new Color4 object
  2094. */
  2095. Color4.prototype.clone = function () {
  2096. return new Color4(this.r, this.g, this.b, this.a);
  2097. };
  2098. /**
  2099. * Copies the passed Color4 values into the current one
  2100. * @param source defines the source Color4 object
  2101. * @returns the current updated Color4 object
  2102. */
  2103. Color4.prototype.copyFrom = function (source) {
  2104. this.r = source.r;
  2105. this.g = source.g;
  2106. this.b = source.b;
  2107. this.a = source.a;
  2108. return this;
  2109. };
  2110. /**
  2111. * Copies the passed float values into the current one
  2112. * @param r defines the red component to read from
  2113. * @param g defines the green component to read from
  2114. * @param b defines the blue component to read from
  2115. * @param a defines the alpha component to read from
  2116. * @returns the current updated Color4 object
  2117. */
  2118. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2119. this.r = r;
  2120. this.g = g;
  2121. this.b = b;
  2122. this.a = a;
  2123. return this;
  2124. };
  2125. /**
  2126. * Copies the passed float values into the current one
  2127. * @param r defines the red component to read from
  2128. * @param g defines the green component to read from
  2129. * @param b defines the blue component to read from
  2130. * @param a defines the alpha component to read from
  2131. * @returns the current updated Color4 object
  2132. */
  2133. Color4.prototype.set = function (r, g, b, a) {
  2134. return this.copyFromFloats(r, g, b, a);
  2135. };
  2136. /**
  2137. * Compute the Color4 hexadecimal code as a string
  2138. * @returns a string containing the hexadecimal representation of the Color4 object
  2139. */
  2140. Color4.prototype.toHexString = function () {
  2141. var intR = (this.r * 255) | 0;
  2142. var intG = (this.g * 255) | 0;
  2143. var intB = (this.b * 255) | 0;
  2144. var intA = (this.a * 255) | 0;
  2145. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2146. };
  2147. /**
  2148. * Computes a new Color4 converted from the current one to linear space
  2149. * @returns a new Color4 object
  2150. */
  2151. Color4.prototype.toLinearSpace = function () {
  2152. var convertedColor = new Color4();
  2153. this.toLinearSpaceToRef(convertedColor);
  2154. return convertedColor;
  2155. };
  2156. /**
  2157. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2158. * @param convertedColor defines the Color4 object where to store the linear space version
  2159. * @returns the unmodified Color4
  2160. */
  2161. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2162. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2163. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2164. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2165. convertedColor.a = this.a;
  2166. return this;
  2167. };
  2168. /**
  2169. * Computes a new Color4 converted from the current one to gamma space
  2170. * @returns a new Color4 object
  2171. */
  2172. Color4.prototype.toGammaSpace = function () {
  2173. var convertedColor = new Color4();
  2174. this.toGammaSpaceToRef(convertedColor);
  2175. return convertedColor;
  2176. };
  2177. /**
  2178. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2179. * @param convertedColor defines the Color4 object where to store the gamma space version
  2180. * @returns the unmodified Color4
  2181. */
  2182. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2183. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2184. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2185. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2186. convertedColor.a = this.a;
  2187. return this;
  2188. };
  2189. // Statics
  2190. /**
  2191. * Creates a new Color4 from the string containing valid hexadecimal values
  2192. * @param hex defines a string containing valid hexadecimal values
  2193. * @returns a new Color4 object
  2194. */
  2195. Color4.FromHexString = function (hex) {
  2196. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2197. return new Color4(0.0, 0.0, 0.0, 0.0);
  2198. }
  2199. var r = parseInt(hex.substring(1, 3), 16);
  2200. var g = parseInt(hex.substring(3, 5), 16);
  2201. var b = parseInt(hex.substring(5, 7), 16);
  2202. var a = parseInt(hex.substring(7, 9), 16);
  2203. return Color4.FromInts(r, g, b, a);
  2204. };
  2205. /**
  2206. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2207. * @param left defines the start value
  2208. * @param right defines the end value
  2209. * @param amount defines the gradient factor
  2210. * @returns a new Color4 object
  2211. */
  2212. Color4.Lerp = function (left, right, amount) {
  2213. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2214. Color4.LerpToRef(left, right, amount, result);
  2215. return result;
  2216. };
  2217. /**
  2218. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2219. * @param left defines the start value
  2220. * @param right defines the end value
  2221. * @param amount defines the gradient factor
  2222. * @param result defines the Color4 object where to store data
  2223. */
  2224. Color4.LerpToRef = function (left, right, amount, result) {
  2225. result.r = left.r + (right.r - left.r) * amount;
  2226. result.g = left.g + (right.g - left.g) * amount;
  2227. result.b = left.b + (right.b - left.b) * amount;
  2228. result.a = left.a + (right.a - left.a) * amount;
  2229. };
  2230. /**
  2231. * Creates a new Color4 from the starting index element of the passed array
  2232. * @param array defines the source array to read from
  2233. * @param offset defines the offset in the source array
  2234. * @returns a new Color4 object
  2235. */
  2236. Color4.FromArray = function (array, offset) {
  2237. if (offset === void 0) { offset = 0; }
  2238. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2239. };
  2240. /**
  2241. * Creates a new Color3 from integer values (< 256)
  2242. * @param r defines the red component to read from (value between 0 and 255)
  2243. * @param g defines the green component to read from (value between 0 and 255)
  2244. * @param b defines the blue component to read from (value between 0 and 255)
  2245. * @param a defines the alpha component to read from (value between 0 and 255)
  2246. * @returns a new Color3 object
  2247. */
  2248. Color4.FromInts = function (r, g, b, a) {
  2249. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2250. };
  2251. /**
  2252. * Check the content of a given array and convert it to an array containing RGBA data
  2253. * If the original array was already containing count * 4 values then it is returned directly
  2254. * @param colors defines the array to check
  2255. * @param count defines the number of RGBA data to expect
  2256. * @returns an array containing count * 4 values (RGBA)
  2257. */
  2258. Color4.CheckColors4 = function (colors, count) {
  2259. // Check if color3 was used
  2260. if (colors.length === count * 3) {
  2261. var colors4 = [];
  2262. for (var index = 0; index < colors.length; index += 3) {
  2263. var newIndex = (index / 3) * 4;
  2264. colors4[newIndex] = colors[index];
  2265. colors4[newIndex + 1] = colors[index + 1];
  2266. colors4[newIndex + 2] = colors[index + 2];
  2267. colors4[newIndex + 3] = 1.0;
  2268. }
  2269. return colors4;
  2270. }
  2271. return colors;
  2272. };
  2273. return Color4;
  2274. }());
  2275. BABYLON.Color4 = Color4;
  2276. var Vector2 = /** @class */ (function () {
  2277. /**
  2278. * Creates a new Vector2 from the passed x and y coordinates.
  2279. */
  2280. function Vector2(x, y) {
  2281. this.x = x;
  2282. this.y = y;
  2283. }
  2284. /**
  2285. * Returns a string with the Vector2 coordinates.
  2286. */
  2287. Vector2.prototype.toString = function () {
  2288. return "{X: " + this.x + " Y:" + this.y + "}";
  2289. };
  2290. /**
  2291. * Returns the string "Vector2"
  2292. */
  2293. Vector2.prototype.getClassName = function () {
  2294. return "Vector2";
  2295. };
  2296. /**
  2297. * Returns the Vector2 hash code as a number.
  2298. */
  2299. Vector2.prototype.getHashCode = function () {
  2300. var hash = this.x || 0;
  2301. hash = (hash * 397) ^ (this.y || 0);
  2302. return hash;
  2303. };
  2304. // Operators
  2305. /**
  2306. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2307. * Returns the Vector2.
  2308. */
  2309. Vector2.prototype.toArray = function (array, index) {
  2310. if (index === void 0) { index = 0; }
  2311. array[index] = this.x;
  2312. array[index + 1] = this.y;
  2313. return this;
  2314. };
  2315. /**
  2316. * Returns a new array with 2 elements : the Vector2 coordinates.
  2317. */
  2318. Vector2.prototype.asArray = function () {
  2319. var result = new Array();
  2320. this.toArray(result, 0);
  2321. return result;
  2322. };
  2323. /**
  2324. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2325. * Returns the updated Vector2.
  2326. */
  2327. Vector2.prototype.copyFrom = function (source) {
  2328. this.x = source.x;
  2329. this.y = source.y;
  2330. return this;
  2331. };
  2332. /**
  2333. * Sets the Vector2 coordinates with the passed floats.
  2334. * Returns the updated Vector2.
  2335. */
  2336. Vector2.prototype.copyFromFloats = function (x, y) {
  2337. this.x = x;
  2338. this.y = y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Sets the Vector2 coordinates with the passed floats.
  2343. * Returns the updated Vector2.
  2344. */
  2345. Vector2.prototype.set = function (x, y) {
  2346. return this.copyFromFloats(x, y);
  2347. };
  2348. /**
  2349. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2350. */
  2351. Vector2.prototype.add = function (otherVector) {
  2352. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2353. };
  2354. /**
  2355. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2356. * Returns the Vector2.
  2357. */
  2358. Vector2.prototype.addToRef = function (otherVector, result) {
  2359. result.x = this.x + otherVector.x;
  2360. result.y = this.y + otherVector.y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2365. * Returns the updated Vector2.
  2366. */
  2367. Vector2.prototype.addInPlace = function (otherVector) {
  2368. this.x += otherVector.x;
  2369. this.y += otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2374. */
  2375. Vector2.prototype.addVector3 = function (otherVector) {
  2376. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2377. };
  2378. /**
  2379. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2380. */
  2381. Vector2.prototype.subtract = function (otherVector) {
  2382. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2383. };
  2384. /**
  2385. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2386. * Returns the Vector2.
  2387. */
  2388. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2389. result.x = this.x - otherVector.x;
  2390. result.y = this.y - otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2395. * Returns the updated Vector2.
  2396. */
  2397. Vector2.prototype.subtractInPlace = function (otherVector) {
  2398. this.x -= otherVector.x;
  2399. this.y -= otherVector.y;
  2400. return this;
  2401. };
  2402. /**
  2403. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2404. * Returns the updated Vector2.
  2405. */
  2406. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2407. this.x *= otherVector.x;
  2408. this.y *= otherVector.y;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2413. */
  2414. Vector2.prototype.multiply = function (otherVector) {
  2415. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2416. };
  2417. /**
  2418. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2419. * Returns the Vector2.
  2420. */
  2421. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2422. result.x = this.x * otherVector.x;
  2423. result.y = this.y * otherVector.y;
  2424. return this;
  2425. };
  2426. /**
  2427. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2428. */
  2429. Vector2.prototype.multiplyByFloats = function (x, y) {
  2430. return new Vector2(this.x * x, this.y * y);
  2431. };
  2432. /**
  2433. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2434. */
  2435. Vector2.prototype.divide = function (otherVector) {
  2436. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2437. };
  2438. /**
  2439. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2440. * Returns the Vector2.
  2441. */
  2442. Vector2.prototype.divideToRef = function (otherVector, result) {
  2443. result.x = this.x / otherVector.x;
  2444. result.y = this.y / otherVector.y;
  2445. return this;
  2446. };
  2447. /**
  2448. * Divides the current Vector3 coordinates by the passed ones.
  2449. * Returns the updated Vector3.
  2450. */
  2451. Vector2.prototype.divideInPlace = function (otherVector) {
  2452. return this.divideToRef(otherVector, this);
  2453. };
  2454. /**
  2455. * Returns a new Vector2 with current Vector2 negated coordinates.
  2456. */
  2457. Vector2.prototype.negate = function () {
  2458. return new Vector2(-this.x, -this.y);
  2459. };
  2460. /**
  2461. * Multiply the Vector2 coordinates by scale.
  2462. * Returns the updated Vector2.
  2463. */
  2464. Vector2.prototype.scaleInPlace = function (scale) {
  2465. this.x *= scale;
  2466. this.y *= scale;
  2467. return this;
  2468. };
  2469. /**
  2470. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2471. */
  2472. Vector2.prototype.scale = function (scale) {
  2473. var result = new Vector2(0, 0);
  2474. this.scaleToRef(scale, result);
  2475. return result;
  2476. };
  2477. /**
  2478. * Scale the current Vector2 values by a factor to a given Vector2
  2479. * @param scale defines the scale factor
  2480. * @param result defines the Vector2 object where to store the result
  2481. * @returns the unmodified current Vector2
  2482. */
  2483. Vector2.prototype.scaleToRef = function (scale, result) {
  2484. result.x = this.x * scale;
  2485. result.y = this.y * scale;
  2486. return this;
  2487. };
  2488. /**
  2489. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2490. * @param scale defines the scale factor
  2491. * @param result defines the Vector2 object where to store the result
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2495. result.x += this.x * scale;
  2496. result.y += this.y * scale;
  2497. return this;
  2498. };
  2499. /**
  2500. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2501. */
  2502. Vector2.prototype.equals = function (otherVector) {
  2503. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2504. };
  2505. /**
  2506. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2507. */
  2508. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2509. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2510. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2511. };
  2512. // Properties
  2513. /**
  2514. * Returns the vector length (float).
  2515. */
  2516. Vector2.prototype.length = function () {
  2517. return Math.sqrt(this.x * this.x + this.y * this.y);
  2518. };
  2519. /**
  2520. * Returns the vector squared length (float);
  2521. */
  2522. Vector2.prototype.lengthSquared = function () {
  2523. return (this.x * this.x + this.y * this.y);
  2524. };
  2525. // Methods
  2526. /**
  2527. * Normalize the vector.
  2528. * Returns the updated Vector2.
  2529. */
  2530. Vector2.prototype.normalize = function () {
  2531. var len = this.length();
  2532. if (len === 0)
  2533. return this;
  2534. var num = 1.0 / len;
  2535. this.x *= num;
  2536. this.y *= num;
  2537. return this;
  2538. };
  2539. /**
  2540. * Returns a new Vector2 copied from the Vector2.
  2541. */
  2542. Vector2.prototype.clone = function () {
  2543. return new Vector2(this.x, this.y);
  2544. };
  2545. // Statics
  2546. /**
  2547. * Returns a new Vector2(0, 0)
  2548. */
  2549. Vector2.Zero = function () {
  2550. return new Vector2(0, 0);
  2551. };
  2552. /**
  2553. * Returns a new Vector2(1, 1)
  2554. */
  2555. Vector2.One = function () {
  2556. return new Vector2(1, 1);
  2557. };
  2558. /**
  2559. * Returns a new Vector2 set from the passed index element of the passed array.
  2560. */
  2561. Vector2.FromArray = function (array, offset) {
  2562. if (offset === void 0) { offset = 0; }
  2563. return new Vector2(array[offset], array[offset + 1]);
  2564. };
  2565. /**
  2566. * Sets "result" from the passed index element of the passed array.
  2567. */
  2568. Vector2.FromArrayToRef = function (array, offset, result) {
  2569. result.x = array[offset];
  2570. result.y = array[offset + 1];
  2571. };
  2572. /**
  2573. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2574. */
  2575. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2576. var squared = amount * amount;
  2577. var cubed = amount * squared;
  2578. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2579. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2580. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2581. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2582. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2583. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2584. return new Vector2(x, y);
  2585. };
  2586. /**
  2587. * 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".
  2588. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2589. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2590. */
  2591. Vector2.Clamp = function (value, min, max) {
  2592. var x = value.x;
  2593. x = (x > max.x) ? max.x : x;
  2594. x = (x < min.x) ? min.x : x;
  2595. var y = value.y;
  2596. y = (y > max.y) ? max.y : y;
  2597. y = (y < min.y) ? min.y : y;
  2598. return new Vector2(x, y);
  2599. };
  2600. /**
  2601. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2602. */
  2603. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2604. var squared = amount * amount;
  2605. var cubed = amount * squared;
  2606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2608. var part3 = (cubed - (2.0 * squared)) + amount;
  2609. var part4 = cubed - squared;
  2610. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2611. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2612. return new Vector2(x, y);
  2613. };
  2614. /**
  2615. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2616. */
  2617. Vector2.Lerp = function (start, end, amount) {
  2618. var x = start.x + ((end.x - start.x) * amount);
  2619. var y = start.y + ((end.y - start.y) * amount);
  2620. return new Vector2(x, y);
  2621. };
  2622. /**
  2623. * Returns the dot product (float) of the vector "left" and the vector "right".
  2624. */
  2625. Vector2.Dot = function (left, right) {
  2626. return left.x * right.x + left.y * right.y;
  2627. };
  2628. /**
  2629. * Returns a new Vector2 equal to the normalized passed vector.
  2630. */
  2631. Vector2.Normalize = function (vector) {
  2632. var newVector = vector.clone();
  2633. newVector.normalize();
  2634. return newVector;
  2635. };
  2636. /**
  2637. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2638. */
  2639. Vector2.Minimize = function (left, right) {
  2640. var x = (left.x < right.x) ? left.x : right.x;
  2641. var y = (left.y < right.y) ? left.y : right.y;
  2642. return new Vector2(x, y);
  2643. };
  2644. /**
  2645. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2646. */
  2647. Vector2.Maximize = function (left, right) {
  2648. var x = (left.x > right.x) ? left.x : right.x;
  2649. var y = (left.y > right.y) ? left.y : right.y;
  2650. return new Vector2(x, y);
  2651. };
  2652. /**
  2653. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2662. */
  2663. Vector2.TransformToRef = function (vector, transformation, result) {
  2664. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2665. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2666. result.x = x;
  2667. result.y = y;
  2668. };
  2669. /**
  2670. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2671. */
  2672. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2673. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2674. var sign = a < 0 ? -1 : 1;
  2675. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2676. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2677. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2678. };
  2679. /**
  2680. * Returns the distance (float) between the vectors "value1" and "value2".
  2681. */
  2682. Vector2.Distance = function (value1, value2) {
  2683. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2684. };
  2685. /**
  2686. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2687. */
  2688. Vector2.DistanceSquared = function (value1, value2) {
  2689. var x = value1.x - value2.x;
  2690. var y = value1.y - value2.y;
  2691. return (x * x) + (y * y);
  2692. };
  2693. /**
  2694. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2695. */
  2696. Vector2.Center = function (value1, value2) {
  2697. var center = value1.add(value2);
  2698. center.scaleInPlace(0.5);
  2699. return center;
  2700. };
  2701. /**
  2702. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2703. */
  2704. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2705. var l2 = Vector2.DistanceSquared(segA, segB);
  2706. if (l2 === 0.0) {
  2707. return Vector2.Distance(p, segA);
  2708. }
  2709. var v = segB.subtract(segA);
  2710. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2711. var proj = segA.add(v.multiplyByFloats(t, t));
  2712. return Vector2.Distance(p, proj);
  2713. };
  2714. return Vector2;
  2715. }());
  2716. BABYLON.Vector2 = Vector2;
  2717. /**
  2718. * Classed used to store (x,y,z) vector representation
  2719. * A Vector3 is the main object used in 3D geometry
  2720. * It can represent etiher the coordinates of a point the space, either a direction
  2721. * Reminder: Babylon.js uses a left handed forward facing system
  2722. */
  2723. var Vector3 = /** @class */ (function () {
  2724. /**
  2725. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2726. * @param x defines the first coordinates (on X axis)
  2727. * @param y defines the second coordinates (on Y axis)
  2728. * @param z defines the third coordinates (on Z axis)
  2729. */
  2730. function Vector3(
  2731. /**
  2732. * Defines the first coordinates (on X axis)
  2733. */
  2734. x,
  2735. /**
  2736. * Defines the second coordinates (on Y axis)
  2737. */
  2738. y,
  2739. /**
  2740. * Defines the third coordinates (on Z axis)
  2741. */
  2742. z) {
  2743. this.x = x;
  2744. this.y = y;
  2745. this.z = z;
  2746. }
  2747. /**
  2748. * Creates a string representation of the Vector3
  2749. * @returns a string with the Vector3 coordinates.
  2750. */
  2751. Vector3.prototype.toString = function () {
  2752. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2753. };
  2754. /**
  2755. * Gets the class name
  2756. * @returns the string "Vector3"
  2757. */
  2758. Vector3.prototype.getClassName = function () {
  2759. return "Vector3";
  2760. };
  2761. /**
  2762. * Creates the Vector3 hash code
  2763. * @returns a number which tends to be unique between Vector3 instances
  2764. */
  2765. Vector3.prototype.getHashCode = function () {
  2766. var hash = this.x || 0;
  2767. hash = (hash * 397) ^ (this.y || 0);
  2768. hash = (hash * 397) ^ (this.z || 0);
  2769. return hash;
  2770. };
  2771. // Operators
  2772. /**
  2773. * Creates an array containing three elements : the coordinates of the Vector3
  2774. * @returns a new array of numbers
  2775. */
  2776. Vector3.prototype.asArray = function () {
  2777. var result = [];
  2778. this.toArray(result, 0);
  2779. return result;
  2780. };
  2781. /**
  2782. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2783. * @param array defines the destination array
  2784. * @param index defines the offset in the destination array
  2785. * @returns the current Vector3
  2786. */
  2787. Vector3.prototype.toArray = function (array, index) {
  2788. if (index === void 0) { index = 0; }
  2789. array[index] = this.x;
  2790. array[index + 1] = this.y;
  2791. array[index + 2] = this.z;
  2792. return this;
  2793. };
  2794. /**
  2795. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2796. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2797. */
  2798. Vector3.prototype.toQuaternion = function () {
  2799. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2800. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2801. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2802. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2803. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2804. var cosy = Math.cos(this.y * 0.5);
  2805. var siny = Math.sin(this.y * 0.5);
  2806. result.x = coszMinusx * siny;
  2807. result.y = -sinzMinusx * siny;
  2808. result.z = sinxPlusz * cosy;
  2809. result.w = cosxPlusz * cosy;
  2810. return result;
  2811. };
  2812. /**
  2813. * Adds the passed vector to the current Vector3
  2814. * @param otherVector defines the second operand
  2815. * @returns the current updated Vector3
  2816. */
  2817. Vector3.prototype.addInPlace = function (otherVector) {
  2818. this.x += otherVector.x;
  2819. this.y += otherVector.y;
  2820. this.z += otherVector.z;
  2821. return this;
  2822. };
  2823. /**
  2824. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2825. * @param otherVector defines the second operand
  2826. * @returns the resulting Vector3
  2827. */
  2828. Vector3.prototype.add = function (otherVector) {
  2829. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2830. };
  2831. /**
  2832. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2833. * @param otherVector defines the second operand
  2834. * @param result defines the Vector3 object where to store the result
  2835. * @returns the current Vector3
  2836. */
  2837. Vector3.prototype.addToRef = function (otherVector, result) {
  2838. result.x = this.x + otherVector.x;
  2839. result.y = this.y + otherVector.y;
  2840. result.z = this.z + otherVector.z;
  2841. return this;
  2842. };
  2843. /**
  2844. * Subtract the passed vector from the current Vector3
  2845. * @param otherVector defines the second operand
  2846. * @returns the current updated Vector3
  2847. */
  2848. Vector3.prototype.subtractInPlace = function (otherVector) {
  2849. this.x -= otherVector.x;
  2850. this.y -= otherVector.y;
  2851. this.z -= otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2856. * @param otherVector defines the second operand
  2857. * @returns the resulting Vector3
  2858. */
  2859. Vector3.prototype.subtract = function (otherVector) {
  2860. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2861. };
  2862. /**
  2863. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2864. * @param otherVector defines the second operand
  2865. * @param result defines the Vector3 object where to store the result
  2866. * @returns the current Vector3
  2867. */
  2868. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2869. result.x = this.x - otherVector.x;
  2870. result.y = this.y - otherVector.y;
  2871. result.z = this.z - otherVector.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2876. * @param x defines the x coordinate of the operand
  2877. * @param y defines the y coordinate of the operand
  2878. * @param z defines the z coordinate of the operand
  2879. * @returns the resulting Vector3
  2880. */
  2881. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2882. return new Vector3(this.x - x, this.y - y, this.z - z);
  2883. };
  2884. /**
  2885. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2886. * @param x defines the x coordinate of the operand
  2887. * @param y defines the y coordinate of the operand
  2888. * @param z defines the z coordinate of the operand
  2889. * @param result defines the Vector3 object where to store the result
  2890. * @returns the current Vector3
  2891. */
  2892. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2893. result.x = this.x - x;
  2894. result.y = this.y - y;
  2895. result.z = this.z - z;
  2896. return this;
  2897. };
  2898. /**
  2899. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2900. * @returns a new Vector3
  2901. */
  2902. Vector3.prototype.negate = function () {
  2903. return new Vector3(-this.x, -this.y, -this.z);
  2904. };
  2905. /**
  2906. * Multiplies the Vector3 coordinates by the float "scale"
  2907. * @param scale defines the multiplier factor
  2908. * @returns the current updated Vector3
  2909. */
  2910. Vector3.prototype.scaleInPlace = function (scale) {
  2911. this.x *= scale;
  2912. this.y *= scale;
  2913. this.z *= scale;
  2914. return this;
  2915. };
  2916. /**
  2917. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2918. * @param scale defines the multiplier factor
  2919. * @returns a new Vector3
  2920. */
  2921. Vector3.prototype.scale = function (scale) {
  2922. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2923. };
  2924. /**
  2925. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2926. * @param scale defines the multiplier factor
  2927. * @param result defines the Vector3 object where to store the result
  2928. * @returns the current Vector3
  2929. */
  2930. Vector3.prototype.scaleToRef = function (scale, result) {
  2931. result.x = this.x * scale;
  2932. result.y = this.y * scale;
  2933. result.z = this.z * scale;
  2934. return this;
  2935. };
  2936. /**
  2937. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2938. * @param scale defines the scale factor
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the unmodified current Vector3
  2941. */
  2942. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2943. result.x += this.x * scale;
  2944. result.y += this.y * scale;
  2945. result.z += this.z * scale;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2950. * @param otherVector defines the second operand
  2951. * @returns true if both vectors are equals
  2952. */
  2953. Vector3.prototype.equals = function (otherVector) {
  2954. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2955. };
  2956. /**
  2957. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2958. * @param otherVector defines the second operand
  2959. * @param epsilon defines the minimal distance to define values as equals
  2960. * @returns true if both vectors are distant less than epsilon
  2961. */
  2962. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2963. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2964. 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);
  2965. };
  2966. /**
  2967. * Returns true if the current Vector3 coordinates equals the passed floats
  2968. * @param x defines the x coordinate of the operand
  2969. * @param y defines the y coordinate of the operand
  2970. * @param z defines the z coordinate of the operand
  2971. * @returns true if both vectors are equals
  2972. */
  2973. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2974. return this.x === x && this.y === y && this.z === z;
  2975. };
  2976. /**
  2977. * Multiplies the current Vector3 coordinates by the passed ones
  2978. * @param otherVector defines the second operand
  2979. * @returns the current updated Vector3
  2980. */
  2981. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2982. this.x *= otherVector.x;
  2983. this.y *= otherVector.y;
  2984. this.z *= otherVector.z;
  2985. return this;
  2986. };
  2987. /**
  2988. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2989. * @param otherVector defines the second operand
  2990. * @returns the new Vector3
  2991. */
  2992. Vector3.prototype.multiply = function (otherVector) {
  2993. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2994. };
  2995. /**
  2996. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2997. * @param otherVector defines the second operand
  2998. * @param result defines the Vector3 object where to store the result
  2999. * @returns the current Vector3
  3000. */
  3001. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3002. result.x = this.x * otherVector.x;
  3003. result.y = this.y * otherVector.y;
  3004. result.z = this.z * otherVector.z;
  3005. return this;
  3006. };
  3007. /**
  3008. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3009. * @param x defines the x coordinate of the operand
  3010. * @param y defines the y coordinate of the operand
  3011. * @param z defines the z coordinate of the operand
  3012. * @returns the new Vector3
  3013. */
  3014. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3015. return new Vector3(this.x * x, this.y * y, this.z * z);
  3016. };
  3017. /**
  3018. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3019. * @param otherVector defines the second operand
  3020. * @returns the new Vector3
  3021. */
  3022. Vector3.prototype.divide = function (otherVector) {
  3023. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3024. };
  3025. /**
  3026. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3027. * @param otherVector defines the second operand
  3028. * @param result defines the Vector3 object where to store the result
  3029. * @returns the current Vector3
  3030. */
  3031. Vector3.prototype.divideToRef = function (otherVector, result) {
  3032. result.x = this.x / otherVector.x;
  3033. result.y = this.y / otherVector.y;
  3034. result.z = this.z / otherVector.z;
  3035. return this;
  3036. };
  3037. /**
  3038. * Divides the current Vector3 coordinates by the passed ones.
  3039. * @param otherVector defines the second operand
  3040. * @returns the current updated Vector3
  3041. */
  3042. Vector3.prototype.divideInPlace = function (otherVector) {
  3043. return this.divideToRef(otherVector, this);
  3044. };
  3045. /**
  3046. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3047. * @param other defines the second operand
  3048. * @returns the current updated Vector3
  3049. */
  3050. Vector3.prototype.minimizeInPlace = function (other) {
  3051. if (other.x < this.x)
  3052. this.x = other.x;
  3053. if (other.y < this.y)
  3054. this.y = other.y;
  3055. if (other.z < this.z)
  3056. this.z = other.z;
  3057. return this;
  3058. };
  3059. /**
  3060. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3061. * @param other defines the second operand
  3062. * @returns the current updated Vector3
  3063. */
  3064. Vector3.prototype.maximizeInPlace = function (other) {
  3065. if (other.x > this.x)
  3066. this.x = other.x;
  3067. if (other.y > this.y)
  3068. this.y = other.y;
  3069. if (other.z > this.z)
  3070. this.z = other.z;
  3071. return this;
  3072. };
  3073. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3074. /**
  3075. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3076. */
  3077. get: function () {
  3078. var absX = Math.abs(this.x);
  3079. var absY = Math.abs(this.y);
  3080. if (absX !== absY) {
  3081. return true;
  3082. }
  3083. var absZ = Math.abs(this.z);
  3084. if (absX !== absZ) {
  3085. return true;
  3086. }
  3087. if (absY !== absZ) {
  3088. return true;
  3089. }
  3090. return false;
  3091. },
  3092. enumerable: true,
  3093. configurable: true
  3094. });
  3095. // Properties
  3096. /**
  3097. * Gets the length of the Vector3
  3098. * @returns the length of the Vecto3
  3099. */
  3100. Vector3.prototype.length = function () {
  3101. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3102. };
  3103. /**
  3104. * Gets the squared length of the Vector3
  3105. * @returns squared length of the Vector3
  3106. */
  3107. Vector3.prototype.lengthSquared = function () {
  3108. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3109. };
  3110. /**
  3111. * Normalize the current Vector3.
  3112. * Please note that this is an in place operation.
  3113. * @returns the current updated Vector3
  3114. */
  3115. Vector3.prototype.normalize = function () {
  3116. var len = this.length();
  3117. if (len === 0 || len === 1.0)
  3118. return this;
  3119. var num = 1.0 / len;
  3120. this.x *= num;
  3121. this.y *= num;
  3122. this.z *= num;
  3123. return this;
  3124. };
  3125. /**
  3126. * Normalize the current Vector3 to a new vector
  3127. * @returns the new Vector3
  3128. */
  3129. Vector3.prototype.normalizeToNew = function () {
  3130. var normalized = new Vector3(0, 0, 0);
  3131. this.normalizeToRef(normalized);
  3132. return normalized;
  3133. };
  3134. /**
  3135. * Normalize the current Vector3 to the reference
  3136. * @param reference define the Vector3 to update
  3137. * @returns the updated Vector3
  3138. */
  3139. Vector3.prototype.normalizeToRef = function (reference) {
  3140. var len = this.length();
  3141. if (len === 0 || len === 1.0) {
  3142. reference.set(this.x, this.y, this.z);
  3143. return reference;
  3144. }
  3145. var scale = 1.0 / len;
  3146. this.scaleToRef(scale, reference);
  3147. return reference;
  3148. };
  3149. /**
  3150. * Creates a new Vector3 copied from the current Vector3
  3151. * @returns the new Vector3
  3152. */
  3153. Vector3.prototype.clone = function () {
  3154. return new Vector3(this.x, this.y, this.z);
  3155. };
  3156. /**
  3157. * Copies the passed vector coordinates to the current Vector3 ones
  3158. * @param source defines the source Vector3
  3159. * @returns the current updated Vector3
  3160. */
  3161. Vector3.prototype.copyFrom = function (source) {
  3162. this.x = source.x;
  3163. this.y = source.y;
  3164. this.z = source.z;
  3165. return this;
  3166. };
  3167. /**
  3168. * Copies the passed floats to the current Vector3 coordinates
  3169. * @param x defines the x coordinate of the operand
  3170. * @param y defines the y coordinate of the operand
  3171. * @param z defines the z coordinate of the operand
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3175. this.x = x;
  3176. this.y = y;
  3177. this.z = z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the passed floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.set = function (x, y, z) {
  3188. return this.copyFromFloats(x, y, z);
  3189. };
  3190. // Statics
  3191. /**
  3192. * Get the clip factor between two vectors
  3193. * @param vector0 defines the first operand
  3194. * @param vector1 defines the second operand
  3195. * @param axis defines the axis to use
  3196. * @param size defines the size along the axis
  3197. * @returns the clip factor
  3198. */
  3199. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3200. var d0 = Vector3.Dot(vector0, axis) - size;
  3201. var d1 = Vector3.Dot(vector1, axis) - size;
  3202. var s = d0 / (d0 - d1);
  3203. return s;
  3204. };
  3205. /**
  3206. * Get angle between two vectors
  3207. * @param vector0 angle between vector0 and vector1
  3208. * @param vector1 angle between vector0 and vector1
  3209. * @param normal direction of the normal
  3210. * @return the angle between vector0 and vector1
  3211. */
  3212. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3213. var v0 = vector0.clone().normalize();
  3214. var v1 = vector1.clone().normalize();
  3215. var dot = Vector3.Dot(v0, v1);
  3216. var n = Vector3.Cross(v0, v1);
  3217. if (Vector3.Dot(n, normal) > 0) {
  3218. return Math.acos(dot);
  3219. }
  3220. return -Math.acos(dot);
  3221. };
  3222. /**
  3223. * Returns a new Vector3 set from the index "offset" of the passed array
  3224. * @param array defines the source array
  3225. * @param offset defines the offset in the source array
  3226. * @returns the new Vector3
  3227. */
  3228. Vector3.FromArray = function (array, offset) {
  3229. if (!offset) {
  3230. offset = 0;
  3231. }
  3232. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3233. };
  3234. /**
  3235. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3236. * This function is deprecated. Use FromArray instead
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromFloatArray = function (array, offset) {
  3242. return Vector3.FromArray(array, offset);
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3246. * @param array defines the source array
  3247. * @param offset defines the offset in the source array
  3248. * @param result defines the Vector3 where to store the result
  3249. */
  3250. Vector3.FromArrayToRef = function (array, offset, result) {
  3251. result.x = array[offset];
  3252. result.y = array[offset + 1];
  3253. result.z = array[offset + 2];
  3254. };
  3255. /**
  3256. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3257. * This function is deprecated. Use FromArrayToRef instead.
  3258. * @param array defines the source array
  3259. * @param offset defines the offset in the source array
  3260. * @param result defines the Vector3 where to store the result
  3261. */
  3262. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3263. return Vector3.FromArrayToRef(array, offset, result);
  3264. };
  3265. /**
  3266. * Sets the passed vector "result" with the passed floats.
  3267. * @param x defines the x coordinate of the source
  3268. * @param y defines the y coordinate of the source
  3269. * @param z defines the z coordinate of the source
  3270. * @param result defines the Vector3 where to store the result
  3271. */
  3272. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3273. result.x = x;
  3274. result.y = y;
  3275. result.z = z;
  3276. };
  3277. /**
  3278. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3279. * @returns a new empty Vector3
  3280. */
  3281. Vector3.Zero = function () {
  3282. return new Vector3(0.0, 0.0, 0.0);
  3283. };
  3284. /**
  3285. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3286. * @returns a new unit Vector3
  3287. */
  3288. Vector3.One = function () {
  3289. return new Vector3(1.0, 1.0, 1.0);
  3290. };
  3291. /**
  3292. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3293. * @returns a new up Vector3
  3294. */
  3295. Vector3.Up = function () {
  3296. return new Vector3(0.0, 1.0, 0.0);
  3297. };
  3298. /**
  3299. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3300. * @returns a new forward Vector3
  3301. */
  3302. Vector3.Forward = function () {
  3303. return new Vector3(0.0, 0.0, 1.0);
  3304. };
  3305. /**
  3306. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3307. * @returns a new right Vector3
  3308. */
  3309. Vector3.Right = function () {
  3310. return new Vector3(1.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3314. * @returns a new left Vector3
  3315. */
  3316. Vector3.Left = function () {
  3317. return new Vector3(-1.0, 0.0, 0.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3321. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3322. * @param vector defines the Vector3 to transform
  3323. * @param transformation defines the transformation matrix
  3324. * @returns the transformed Vector3
  3325. */
  3326. Vector3.TransformCoordinates = function (vector, transformation) {
  3327. var result = Vector3.Zero();
  3328. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3329. return result;
  3330. };
  3331. /**
  3332. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3333. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3334. * @param vector defines the Vector3 to transform
  3335. * @param transformation defines the transformation matrix
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3339. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3340. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3341. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3342. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3343. result.x = x / w;
  3344. result.y = y / w;
  3345. result.z = z / w;
  3346. };
  3347. /**
  3348. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3349. * This method computes tranformed coordinates only, not transformed direction vectors
  3350. * @param x define the x coordinate of the source vector
  3351. * @param y define the y coordinate of the source vector
  3352. * @param z define the z coordinate of the source vector
  3353. * @param transformation defines the transformation matrix
  3354. * @param result defines the Vector3 where to store the result
  3355. */
  3356. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3357. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3358. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3359. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3360. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3361. result.x = rx / rw;
  3362. result.y = ry / rw;
  3363. result.z = rz / rw;
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3367. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3368. * @param vector defines the Vector3 to transform
  3369. * @param transformation defines the transformation matrix
  3370. * @returns the new Vector3
  3371. */
  3372. Vector3.TransformNormal = function (vector, transformation) {
  3373. var result = Vector3.Zero();
  3374. Vector3.TransformNormalToRef(vector, transformation, result);
  3375. return result;
  3376. };
  3377. /**
  3378. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3379. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3380. * @param vector defines the Vector3 to transform
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3385. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3386. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3387. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3388. result.x = x;
  3389. result.y = y;
  3390. result.z = z;
  3391. };
  3392. /**
  3393. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3394. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3395. * @param x define the x coordinate of the source vector
  3396. * @param y define the y coordinate of the source vector
  3397. * @param z define the z coordinate of the source vector
  3398. * @param transformation defines the transformation matrix
  3399. * @param result defines the Vector3 where to store the result
  3400. */
  3401. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3402. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3403. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3404. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3408. * @param value1 defines the first control point
  3409. * @param value2 defines the second control point
  3410. * @param value3 defines the third control point
  3411. * @param value4 defines the fourth control point
  3412. * @param amount defines the amount on the spline to use
  3413. * @returns the new Vector3
  3414. */
  3415. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3416. var squared = amount * amount;
  3417. var cubed = amount * squared;
  3418. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3419. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3420. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3421. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3422. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3423. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3424. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3425. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3426. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3427. return new Vector3(x, y, z);
  3428. };
  3429. /**
  3430. * 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"
  3431. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3432. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3433. * @param value defines the current value
  3434. * @param min defines the lower range value
  3435. * @param max defines the upper range value
  3436. * @returns the new Vector3
  3437. */
  3438. Vector3.Clamp = function (value, min, max) {
  3439. var x = value.x;
  3440. x = (x > max.x) ? max.x : x;
  3441. x = (x < min.x) ? min.x : x;
  3442. var y = value.y;
  3443. y = (y > max.y) ? max.y : y;
  3444. y = (y < min.y) ? min.y : y;
  3445. var z = value.z;
  3446. z = (z > max.z) ? max.z : z;
  3447. z = (z < min.z) ? min.z : z;
  3448. return new Vector3(x, y, z);
  3449. };
  3450. /**
  3451. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3452. * @param value1 defines the first control point
  3453. * @param tangent1 defines the first tangent vector
  3454. * @param value2 defines the second control point
  3455. * @param tangent2 defines the second tangent vector
  3456. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3457. * @returns the new Vector3
  3458. */
  3459. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3460. var squared = amount * amount;
  3461. var cubed = amount * squared;
  3462. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3463. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3464. var part3 = (cubed - (2.0 * squared)) + amount;
  3465. var part4 = cubed - squared;
  3466. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3467. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3468. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3469. return new Vector3(x, y, z);
  3470. };
  3471. /**
  3472. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3473. * @param start defines the start value
  3474. * @param end defines the end value
  3475. * @param amount max defines amount between both (between 0 and 1)
  3476. * @returns the new Vector3
  3477. */
  3478. Vector3.Lerp = function (start, end, amount) {
  3479. var result = new Vector3(0, 0, 0);
  3480. Vector3.LerpToRef(start, end, amount, result);
  3481. return result;
  3482. };
  3483. /**
  3484. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3485. * @param start defines the start value
  3486. * @param end defines the end value
  3487. * @param amount max defines amount between both (between 0 and 1)
  3488. * @param result defines the Vector3 where to store the result
  3489. */
  3490. Vector3.LerpToRef = function (start, end, amount, result) {
  3491. result.x = start.x + ((end.x - start.x) * amount);
  3492. result.y = start.y + ((end.y - start.y) * amount);
  3493. result.z = start.z + ((end.z - start.z) * amount);
  3494. };
  3495. /**
  3496. * Returns the dot product (float) between the vectors "left" and "right"
  3497. * @param left defines the left operand
  3498. * @param right defines the right operand
  3499. * @returns the dot product
  3500. */
  3501. Vector3.Dot = function (left, right) {
  3502. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3503. };
  3504. /**
  3505. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3506. * The cross product is then orthogonal to both "left" and "right"
  3507. * @param left defines the left operand
  3508. * @param right defines the right operand
  3509. * @returns the cross product
  3510. */
  3511. Vector3.Cross = function (left, right) {
  3512. var result = Vector3.Zero();
  3513. Vector3.CrossToRef(left, right, result);
  3514. return result;
  3515. };
  3516. /**
  3517. * Sets the passed vector "result" with the cross product of "left" and "right"
  3518. * The cross product is then orthogonal to both "left" and "right"
  3519. * @param left defines the left operand
  3520. * @param right defines the right operand
  3521. * @param result defines the Vector3 where to store the result
  3522. */
  3523. Vector3.CrossToRef = function (left, right, result) {
  3524. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3525. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3526. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3527. result.copyFrom(MathTmp.Vector3[0]);
  3528. };
  3529. /**
  3530. * Returns a new Vector3 as the normalization of the passed vector
  3531. * @param vector defines the Vector3 to normalize
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Normalize = function (vector) {
  3535. var result = Vector3.Zero();
  3536. Vector3.NormalizeToRef(vector, result);
  3537. return result;
  3538. };
  3539. /**
  3540. * Sets the passed vector "result" with the normalization of the passed first vector
  3541. * @param vector defines the Vector3 to normalize
  3542. * @param result defines the Vector3 where to store the result
  3543. */
  3544. Vector3.NormalizeToRef = function (vector, result) {
  3545. result.copyFrom(vector);
  3546. result.normalize();
  3547. };
  3548. /**
  3549. * Project a Vector3 onto screen space
  3550. * @param vector defines the Vector3 to project
  3551. * @param world defines the world matrix to use
  3552. * @param transform defines the transform (view x projection) matrix to use
  3553. * @param viewport defines the screen viewport to use
  3554. * @returns the new Vector3
  3555. */
  3556. Vector3.Project = function (vector, world, transform, viewport) {
  3557. var cw = viewport.width;
  3558. var ch = viewport.height;
  3559. var cx = viewport.x;
  3560. var cy = viewport.y;
  3561. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3562. 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);
  3563. var matrix = MathTmp.Matrix[0];
  3564. world.multiplyToRef(transform, matrix);
  3565. matrix.multiplyToRef(viewportMatrix, matrix);
  3566. return Vector3.TransformCoordinates(vector, matrix);
  3567. };
  3568. /**
  3569. * Unproject from screen space to object space
  3570. * @param source defines the screen space Vector3 to use
  3571. * @param viewportWidth defines the current width of the viewport
  3572. * @param viewportHeight defines the current height of the viewport
  3573. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3574. * @param transform defines the transform (view x projection) matrix to use
  3575. * @returns the new Vector3
  3576. */
  3577. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3578. var matrix = MathTmp.Matrix[0];
  3579. world.multiplyToRef(transform, matrix);
  3580. matrix.invert();
  3581. source.x = source.x / viewportWidth * 2 - 1;
  3582. source.y = -(source.y / viewportHeight * 2 - 1);
  3583. var vector = Vector3.TransformCoordinates(source, matrix);
  3584. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3585. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3586. vector = vector.scale(1.0 / num);
  3587. }
  3588. return vector;
  3589. };
  3590. /**
  3591. * Unproject from screen space to object space
  3592. * @param source defines the screen space Vector3 to use
  3593. * @param viewportWidth defines the current width of the viewport
  3594. * @param viewportHeight defines the current height of the viewport
  3595. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3596. * @param view defines the view matrix to use
  3597. * @param projection defines the projection matrix to use
  3598. * @returns the new Vector3
  3599. */
  3600. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3601. var result = Vector3.Zero();
  3602. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Unproject from screen space to object space
  3607. * @param source defines the screen space Vector3 to use
  3608. * @param viewportWidth defines the current width of the viewport
  3609. * @param viewportHeight defines the current height of the viewport
  3610. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3611. * @param view defines the view matrix to use
  3612. * @param projection defines the projection matrix to use
  3613. * @param result defines the Vector3 where to store the result
  3614. */
  3615. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3616. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3617. };
  3618. /**
  3619. * Unproject from screen space to object space
  3620. * @param sourceX defines the screen space x coordinate to use
  3621. * @param sourceY defines the screen space y coordinate to use
  3622. * @param sourceZ defines the screen space z coordinate to use
  3623. * @param viewportWidth defines the current width of the viewport
  3624. * @param viewportHeight defines the current height of the viewport
  3625. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3626. * @param view defines the view matrix to use
  3627. * @param projection defines the projection matrix to use
  3628. * @param result defines the Vector3 where to store the result
  3629. */
  3630. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3631. var matrix = MathTmp.Matrix[0];
  3632. world.multiplyToRef(view, matrix);
  3633. matrix.multiplyToRef(projection, matrix);
  3634. matrix.invert();
  3635. var screenSource = MathTmp.Vector3[0];
  3636. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3637. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3638. screenSource.z = 2 * sourceZ - 1.0;
  3639. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3640. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3641. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3642. result.scaleInPlace(1.0 / num);
  3643. }
  3644. };
  3645. /**
  3646. * Gets the minimal coordinate values between two Vector3
  3647. * @param left defines the first operand
  3648. * @param right defines the second operand
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Minimize = function (left, right) {
  3652. var min = left.clone();
  3653. min.minimizeInPlace(right);
  3654. return min;
  3655. };
  3656. /**
  3657. * Gets the maximal coordinate values between two Vector3
  3658. * @param left defines the first operand
  3659. * @param right defines the second operand
  3660. * @returns the new Vector3
  3661. */
  3662. Vector3.Maximize = function (left, right) {
  3663. var max = left.clone();
  3664. max.maximizeInPlace(right);
  3665. return max;
  3666. };
  3667. /**
  3668. * Returns the distance between the vectors "value1" and "value2"
  3669. * @param value1 defines the first operand
  3670. * @param value2 defines the second operand
  3671. * @returns the distance
  3672. */
  3673. Vector3.Distance = function (value1, value2) {
  3674. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3675. };
  3676. /**
  3677. * Returns the squared distance between the vectors "value1" and "value2"
  3678. * @param value1 defines the first operand
  3679. * @param value2 defines the second operand
  3680. * @returns the squared distance
  3681. */
  3682. Vector3.DistanceSquared = function (value1, value2) {
  3683. var x = value1.x - value2.x;
  3684. var y = value1.y - value2.y;
  3685. var z = value1.z - value2.z;
  3686. return (x * x) + (y * y) + (z * z);
  3687. };
  3688. /**
  3689. * Returns a new Vector3 located at the center between "value1" and "value2"
  3690. * @param value1 defines the first operand
  3691. * @param value2 defines the second operand
  3692. * @returns the new Vector3
  3693. */
  3694. Vector3.Center = function (value1, value2) {
  3695. var center = value1.add(value2);
  3696. center.scaleInPlace(0.5);
  3697. return center;
  3698. };
  3699. /**
  3700. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3701. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3702. * to something in order to rotate it from its local system to the given target system
  3703. * Note: axis1, axis2 and axis3 are normalized during this operation
  3704. * @param axis1 defines the first axis
  3705. * @param axis2 defines the second axis
  3706. * @param axis3 defines the third axis
  3707. * @returns a new Vector3
  3708. */
  3709. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3710. var rotation = Vector3.Zero();
  3711. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3712. return rotation;
  3713. };
  3714. /**
  3715. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3716. * @param axis1 defines the first axis
  3717. * @param axis2 defines the second axis
  3718. * @param axis3 defines the third axis
  3719. * @param ref defines the Vector3 where to store the result
  3720. */
  3721. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3722. var quat = MathTmp.Quaternion[0];
  3723. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3724. quat.toEulerAnglesToRef(ref);
  3725. };
  3726. return Vector3;
  3727. }());
  3728. BABYLON.Vector3 = Vector3;
  3729. //Vector4 class created for EulerAngle class conversion to Quaternion
  3730. var Vector4 = /** @class */ (function () {
  3731. /**
  3732. * Creates a Vector4 object from the passed floats.
  3733. */
  3734. function Vector4(x, y, z, w) {
  3735. this.x = x;
  3736. this.y = y;
  3737. this.z = z;
  3738. this.w = w;
  3739. }
  3740. /**
  3741. * Returns the string with the Vector4 coordinates.
  3742. */
  3743. Vector4.prototype.toString = function () {
  3744. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3745. };
  3746. /**
  3747. * Returns the string "Vector4".
  3748. */
  3749. Vector4.prototype.getClassName = function () {
  3750. return "Vector4";
  3751. };
  3752. /**
  3753. * Returns the Vector4 hash code.
  3754. */
  3755. Vector4.prototype.getHashCode = function () {
  3756. var hash = this.x || 0;
  3757. hash = (hash * 397) ^ (this.y || 0);
  3758. hash = (hash * 397) ^ (this.z || 0);
  3759. hash = (hash * 397) ^ (this.w || 0);
  3760. return hash;
  3761. };
  3762. // Operators
  3763. /**
  3764. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3765. */
  3766. Vector4.prototype.asArray = function () {
  3767. var result = new Array();
  3768. this.toArray(result, 0);
  3769. return result;
  3770. };
  3771. /**
  3772. * Populates the passed array from the passed index with the Vector4 coordinates.
  3773. * Returns the Vector4.
  3774. */
  3775. Vector4.prototype.toArray = function (array, index) {
  3776. if (index === undefined) {
  3777. index = 0;
  3778. }
  3779. array[index] = this.x;
  3780. array[index + 1] = this.y;
  3781. array[index + 2] = this.z;
  3782. array[index + 3] = this.w;
  3783. return this;
  3784. };
  3785. /**
  3786. * Adds the passed vector to the current Vector4.
  3787. * Returns the updated Vector4.
  3788. */
  3789. Vector4.prototype.addInPlace = function (otherVector) {
  3790. this.x += otherVector.x;
  3791. this.y += otherVector.y;
  3792. this.z += otherVector.z;
  3793. this.w += otherVector.w;
  3794. return this;
  3795. };
  3796. /**
  3797. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3798. */
  3799. Vector4.prototype.add = function (otherVector) {
  3800. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3801. };
  3802. /**
  3803. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3804. * Returns the current Vector4.
  3805. */
  3806. Vector4.prototype.addToRef = function (otherVector, result) {
  3807. result.x = this.x + otherVector.x;
  3808. result.y = this.y + otherVector.y;
  3809. result.z = this.z + otherVector.z;
  3810. result.w = this.w + otherVector.w;
  3811. return this;
  3812. };
  3813. /**
  3814. * Subtract in place the passed vector from the current Vector4.
  3815. * Returns the updated Vector4.
  3816. */
  3817. Vector4.prototype.subtractInPlace = function (otherVector) {
  3818. this.x -= otherVector.x;
  3819. this.y -= otherVector.y;
  3820. this.z -= otherVector.z;
  3821. this.w -= otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3826. */
  3827. Vector4.prototype.subtract = function (otherVector) {
  3828. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3829. };
  3830. /**
  3831. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3832. * Returns the current Vector4.
  3833. */
  3834. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3835. result.x = this.x - otherVector.x;
  3836. result.y = this.y - otherVector.y;
  3837. result.z = this.z - otherVector.z;
  3838. result.w = this.w - otherVector.w;
  3839. return this;
  3840. };
  3841. /**
  3842. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3845. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3846. };
  3847. /**
  3848. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3849. * Returns the current Vector4.
  3850. */
  3851. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3852. result.x = this.x - x;
  3853. result.y = this.y - y;
  3854. result.z = this.z - z;
  3855. result.w = this.w - w;
  3856. return this;
  3857. };
  3858. /**
  3859. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3860. */
  3861. Vector4.prototype.negate = function () {
  3862. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3863. };
  3864. /**
  3865. * Multiplies the current Vector4 coordinates by scale (float).
  3866. * Returns the updated Vector4.
  3867. */
  3868. Vector4.prototype.scaleInPlace = function (scale) {
  3869. this.x *= scale;
  3870. this.y *= scale;
  3871. this.z *= scale;
  3872. this.w *= scale;
  3873. return this;
  3874. };
  3875. /**
  3876. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3877. */
  3878. Vector4.prototype.scale = function (scale) {
  3879. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3880. };
  3881. /**
  3882. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3883. * Returns the current Vector4.
  3884. */
  3885. Vector4.prototype.scaleToRef = function (scale, result) {
  3886. result.x = this.x * scale;
  3887. result.y = this.y * scale;
  3888. result.z = this.z * scale;
  3889. result.w = this.w * scale;
  3890. return this;
  3891. };
  3892. /**
  3893. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3894. * @param scale defines the scale factor
  3895. * @param result defines the Vector4 object where to store the result
  3896. * @returns the unmodified current Vector4
  3897. */
  3898. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3899. result.x += this.x * scale;
  3900. result.y += this.y * scale;
  3901. result.z += this.z * scale;
  3902. result.w += this.w * scale;
  3903. return this;
  3904. };
  3905. /**
  3906. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3907. */
  3908. Vector4.prototype.equals = function (otherVector) {
  3909. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3910. };
  3911. /**
  3912. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3913. */
  3914. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3915. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3916. return otherVector
  3917. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3918. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3919. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3920. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3921. };
  3922. /**
  3923. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3924. */
  3925. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3926. return this.x === x && this.y === y && this.z === z && this.w === w;
  3927. };
  3928. /**
  3929. * Multiplies in place the current Vector4 by the passed one.
  3930. * Returns the updated Vector4.
  3931. */
  3932. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3933. this.x *= otherVector.x;
  3934. this.y *= otherVector.y;
  3935. this.z *= otherVector.z;
  3936. this.w *= otherVector.w;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3941. */
  3942. Vector4.prototype.multiply = function (otherVector) {
  3943. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3944. };
  3945. /**
  3946. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3947. * Returns the current Vector4.
  3948. */
  3949. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3950. result.x = this.x * otherVector.x;
  3951. result.y = this.y * otherVector.y;
  3952. result.z = this.z * otherVector.z;
  3953. result.w = this.w * otherVector.w;
  3954. return this;
  3955. };
  3956. /**
  3957. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3958. */
  3959. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3960. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3961. };
  3962. /**
  3963. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3964. */
  3965. Vector4.prototype.divide = function (otherVector) {
  3966. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3967. };
  3968. /**
  3969. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3970. * Returns the current Vector4.
  3971. */
  3972. Vector4.prototype.divideToRef = function (otherVector, result) {
  3973. result.x = this.x / otherVector.x;
  3974. result.y = this.y / otherVector.y;
  3975. result.z = this.z / otherVector.z;
  3976. result.w = this.w / otherVector.w;
  3977. return this;
  3978. };
  3979. /**
  3980. * Divides the current Vector3 coordinates by the passed ones.
  3981. * @returns the updated Vector3.
  3982. */
  3983. Vector4.prototype.divideInPlace = function (otherVector) {
  3984. return this.divideToRef(otherVector, this);
  3985. };
  3986. /**
  3987. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3988. * @param other defines the second operand
  3989. * @returns the current updated Vector4
  3990. */
  3991. Vector4.prototype.minimizeInPlace = function (other) {
  3992. if (other.x < this.x)
  3993. this.x = other.x;
  3994. if (other.y < this.y)
  3995. this.y = other.y;
  3996. if (other.z < this.z)
  3997. this.z = other.z;
  3998. if (other.w < this.w)
  3999. this.w = other.w;
  4000. return this;
  4001. };
  4002. /**
  4003. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4004. * @param other defines the second operand
  4005. * @returns the current updated Vector4
  4006. */
  4007. Vector4.prototype.maximizeInPlace = function (other) {
  4008. if (other.x > this.x)
  4009. this.x = other.x;
  4010. if (other.y > this.y)
  4011. this.y = other.y;
  4012. if (other.z > this.z)
  4013. this.z = other.z;
  4014. if (other.w > this.w)
  4015. this.w = other.w;
  4016. return this;
  4017. };
  4018. // Properties
  4019. /**
  4020. * Returns the Vector4 length (float).
  4021. */
  4022. Vector4.prototype.length = function () {
  4023. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4024. };
  4025. /**
  4026. * Returns the Vector4 squared length (float).
  4027. */
  4028. Vector4.prototype.lengthSquared = function () {
  4029. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4030. };
  4031. // Methods
  4032. /**
  4033. * Normalizes in place the Vector4.
  4034. * Returns the updated Vector4.
  4035. */
  4036. Vector4.prototype.normalize = function () {
  4037. var len = this.length();
  4038. if (len === 0)
  4039. return this;
  4040. var num = 1.0 / len;
  4041. this.x *= num;
  4042. this.y *= num;
  4043. this.z *= num;
  4044. this.w *= num;
  4045. return this;
  4046. };
  4047. /**
  4048. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4049. */
  4050. Vector4.prototype.toVector3 = function () {
  4051. return new Vector3(this.x, this.y, this.z);
  4052. };
  4053. /**
  4054. * Returns a new Vector4 copied from the current one.
  4055. */
  4056. Vector4.prototype.clone = function () {
  4057. return new Vector4(this.x, this.y, this.z, this.w);
  4058. };
  4059. /**
  4060. * Updates the current Vector4 with the passed one coordinates.
  4061. * Returns the updated Vector4.
  4062. */
  4063. Vector4.prototype.copyFrom = function (source) {
  4064. this.x = source.x;
  4065. this.y = source.y;
  4066. this.z = source.z;
  4067. this.w = source.w;
  4068. return this;
  4069. };
  4070. /**
  4071. * Updates the current Vector4 coordinates with the passed floats.
  4072. * Returns the updated Vector4.
  4073. */
  4074. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4075. this.x = x;
  4076. this.y = y;
  4077. this.z = z;
  4078. this.w = w;
  4079. return this;
  4080. };
  4081. /**
  4082. * Updates the current Vector4 coordinates with the passed floats.
  4083. * Returns the updated Vector4.
  4084. */
  4085. Vector4.prototype.set = function (x, y, z, w) {
  4086. return this.copyFromFloats(x, y, z, w);
  4087. };
  4088. // Statics
  4089. /**
  4090. * Returns a new Vector4 set from the starting index of the passed array.
  4091. */
  4092. Vector4.FromArray = function (array, offset) {
  4093. if (!offset) {
  4094. offset = 0;
  4095. }
  4096. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4097. };
  4098. /**
  4099. * Updates the passed vector "result" from the starting index of the passed array.
  4100. */
  4101. Vector4.FromArrayToRef = function (array, offset, result) {
  4102. result.x = array[offset];
  4103. result.y = array[offset + 1];
  4104. result.z = array[offset + 2];
  4105. result.w = array[offset + 3];
  4106. };
  4107. /**
  4108. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4109. */
  4110. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4111. Vector4.FromArrayToRef(array, offset, result);
  4112. };
  4113. /**
  4114. * Updates the passed vector "result" coordinates from the passed floats.
  4115. */
  4116. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4117. result.x = x;
  4118. result.y = y;
  4119. result.z = z;
  4120. result.w = w;
  4121. };
  4122. /**
  4123. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4124. */
  4125. Vector4.Zero = function () {
  4126. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4127. };
  4128. /**
  4129. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4130. */
  4131. Vector4.One = function () {
  4132. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4133. };
  4134. /**
  4135. * Returns a new normalized Vector4 from the passed one.
  4136. */
  4137. Vector4.Normalize = function (vector) {
  4138. var result = Vector4.Zero();
  4139. Vector4.NormalizeToRef(vector, result);
  4140. return result;
  4141. };
  4142. /**
  4143. * Updates the passed vector "result" from the normalization of the passed one.
  4144. */
  4145. Vector4.NormalizeToRef = function (vector, result) {
  4146. result.copyFrom(vector);
  4147. result.normalize();
  4148. };
  4149. Vector4.Minimize = function (left, right) {
  4150. var min = left.clone();
  4151. min.minimizeInPlace(right);
  4152. return min;
  4153. };
  4154. Vector4.Maximize = function (left, right) {
  4155. var max = left.clone();
  4156. max.maximizeInPlace(right);
  4157. return max;
  4158. };
  4159. /**
  4160. * Returns the distance (float) between the vectors "value1" and "value2".
  4161. */
  4162. Vector4.Distance = function (value1, value2) {
  4163. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4164. };
  4165. /**
  4166. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4167. */
  4168. Vector4.DistanceSquared = function (value1, value2) {
  4169. var x = value1.x - value2.x;
  4170. var y = value1.y - value2.y;
  4171. var z = value1.z - value2.z;
  4172. var w = value1.w - value2.w;
  4173. return (x * x) + (y * y) + (z * z) + (w * w);
  4174. };
  4175. /**
  4176. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4177. */
  4178. Vector4.Center = function (value1, value2) {
  4179. var center = value1.add(value2);
  4180. center.scaleInPlace(0.5);
  4181. return center;
  4182. };
  4183. /**
  4184. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4185. * This methods computes transformed normalized direction vectors only.
  4186. */
  4187. Vector4.TransformNormal = function (vector, transformation) {
  4188. var result = Vector4.Zero();
  4189. Vector4.TransformNormalToRef(vector, transformation, result);
  4190. return result;
  4191. };
  4192. /**
  4193. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4194. * This methods computes transformed normalized direction vectors only.
  4195. */
  4196. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4197. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4198. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4199. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4200. result.x = x;
  4201. result.y = y;
  4202. result.z = z;
  4203. result.w = vector.w;
  4204. };
  4205. /**
  4206. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4207. * This methods computes transformed normalized direction vectors only.
  4208. */
  4209. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4210. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4211. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4212. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4213. result.w = w;
  4214. };
  4215. return Vector4;
  4216. }());
  4217. BABYLON.Vector4 = Vector4;
  4218. var Size = /** @class */ (function () {
  4219. /**
  4220. * Creates a Size object from the passed width and height (floats).
  4221. */
  4222. function Size(width, height) {
  4223. this.width = width;
  4224. this.height = height;
  4225. }
  4226. // Returns a string with the Size width and height.
  4227. Size.prototype.toString = function () {
  4228. return "{W: " + this.width + ", H: " + this.height + "}";
  4229. };
  4230. /**
  4231. * Returns the string "Size"
  4232. */
  4233. Size.prototype.getClassName = function () {
  4234. return "Size";
  4235. };
  4236. /**
  4237. * Returns the Size hash code.
  4238. */
  4239. Size.prototype.getHashCode = function () {
  4240. var hash = this.width || 0;
  4241. hash = (hash * 397) ^ (this.height || 0);
  4242. return hash;
  4243. };
  4244. /**
  4245. * Updates the current size from the passed one.
  4246. * Returns the updated Size.
  4247. */
  4248. Size.prototype.copyFrom = function (src) {
  4249. this.width = src.width;
  4250. this.height = src.height;
  4251. };
  4252. /**
  4253. * Updates in place the current Size from the passed floats.
  4254. * Returns the updated Size.
  4255. */
  4256. Size.prototype.copyFromFloats = function (width, height) {
  4257. this.width = width;
  4258. this.height = height;
  4259. return this;
  4260. };
  4261. /**
  4262. * Updates in place the current Size from the passed floats.
  4263. * Returns the updated Size.
  4264. */
  4265. Size.prototype.set = function (width, height) {
  4266. return this.copyFromFloats(width, height);
  4267. };
  4268. /**
  4269. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4270. */
  4271. Size.prototype.multiplyByFloats = function (w, h) {
  4272. return new Size(this.width * w, this.height * h);
  4273. };
  4274. /**
  4275. * Returns a new Size copied from the passed one.
  4276. */
  4277. Size.prototype.clone = function () {
  4278. return new Size(this.width, this.height);
  4279. };
  4280. /**
  4281. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4282. */
  4283. Size.prototype.equals = function (other) {
  4284. if (!other) {
  4285. return false;
  4286. }
  4287. return (this.width === other.width) && (this.height === other.height);
  4288. };
  4289. Object.defineProperty(Size.prototype, "surface", {
  4290. /**
  4291. * Returns the surface of the Size : width * height (float).
  4292. */
  4293. get: function () {
  4294. return this.width * this.height;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. /**
  4300. * Returns a new Size set to (0.0, 0.0)
  4301. */
  4302. Size.Zero = function () {
  4303. return new Size(0.0, 0.0);
  4304. };
  4305. /**
  4306. * Returns a new Size set as the addition result of the current Size and the passed one.
  4307. */
  4308. Size.prototype.add = function (otherSize) {
  4309. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4310. return r;
  4311. };
  4312. /**
  4313. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4314. */
  4315. Size.prototype.subtract = function (otherSize) {
  4316. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4317. return r;
  4318. };
  4319. /**
  4320. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4321. */
  4322. Size.Lerp = function (start, end, amount) {
  4323. var w = start.width + ((end.width - start.width) * amount);
  4324. var h = start.height + ((end.height - start.height) * amount);
  4325. return new Size(w, h);
  4326. };
  4327. return Size;
  4328. }());
  4329. BABYLON.Size = Size;
  4330. var Quaternion = /** @class */ (function () {
  4331. /**
  4332. * Creates a new Quaternion from the passed floats.
  4333. */
  4334. function Quaternion(x, y, z, w) {
  4335. if (x === void 0) { x = 0.0; }
  4336. if (y === void 0) { y = 0.0; }
  4337. if (z === void 0) { z = 0.0; }
  4338. if (w === void 0) { w = 1.0; }
  4339. this.x = x;
  4340. this.y = y;
  4341. this.z = z;
  4342. this.w = w;
  4343. }
  4344. /**
  4345. * Returns a string with the Quaternion coordinates.
  4346. */
  4347. Quaternion.prototype.toString = function () {
  4348. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4349. };
  4350. /**
  4351. * Returns the string "Quaternion".
  4352. */
  4353. Quaternion.prototype.getClassName = function () {
  4354. return "Quaternion";
  4355. };
  4356. /**
  4357. * Returns the Quaternion hash code.
  4358. */
  4359. Quaternion.prototype.getHashCode = function () {
  4360. var hash = this.x || 0;
  4361. hash = (hash * 397) ^ (this.y || 0);
  4362. hash = (hash * 397) ^ (this.z || 0);
  4363. hash = (hash * 397) ^ (this.w || 0);
  4364. return hash;
  4365. };
  4366. /**
  4367. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4368. */
  4369. Quaternion.prototype.asArray = function () {
  4370. return [this.x, this.y, this.z, this.w];
  4371. };
  4372. /**
  4373. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4374. */
  4375. Quaternion.prototype.equals = function (otherQuaternion) {
  4376. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4377. };
  4378. /**
  4379. * Returns a new Quaternion copied from the current one.
  4380. */
  4381. Quaternion.prototype.clone = function () {
  4382. return new Quaternion(this.x, this.y, this.z, this.w);
  4383. };
  4384. /**
  4385. * Updates the current Quaternion from the passed one coordinates.
  4386. * Returns the updated Quaterion.
  4387. */
  4388. Quaternion.prototype.copyFrom = function (other) {
  4389. this.x = other.x;
  4390. this.y = other.y;
  4391. this.z = other.z;
  4392. this.w = other.w;
  4393. return this;
  4394. };
  4395. /**
  4396. * Updates the current Quaternion from the passed float coordinates.
  4397. * Returns the updated Quaterion.
  4398. */
  4399. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4400. this.x = x;
  4401. this.y = y;
  4402. this.z = z;
  4403. this.w = w;
  4404. return this;
  4405. };
  4406. /**
  4407. * Updates the current Quaternion from the passed float coordinates.
  4408. * Returns the updated Quaterion.
  4409. */
  4410. Quaternion.prototype.set = function (x, y, z, w) {
  4411. return this.copyFromFloats(x, y, z, w);
  4412. };
  4413. /**
  4414. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4415. */
  4416. Quaternion.prototype.add = function (other) {
  4417. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4418. };
  4419. /**
  4420. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4421. */
  4422. Quaternion.prototype.subtract = function (other) {
  4423. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4424. };
  4425. /**
  4426. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4427. */
  4428. Quaternion.prototype.scale = function (value) {
  4429. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4430. };
  4431. /**
  4432. * Scale the current Quaternion values by a factor to a given Quaternion
  4433. * @param scale defines the scale factor
  4434. * @param result defines the Quaternion object where to store the result
  4435. * @returns the unmodified current Quaternion
  4436. */
  4437. Quaternion.prototype.scaleToRef = function (scale, result) {
  4438. result.x = this.x * scale;
  4439. result.y = this.y * scale;
  4440. result.z = this.z * scale;
  4441. result.w = this.w * scale;
  4442. return this;
  4443. };
  4444. /**
  4445. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4446. * @param scale defines the scale factor
  4447. * @param result defines the Quaternion object where to store the result
  4448. * @returns the unmodified current Quaternion
  4449. */
  4450. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4451. result.x += this.x * scale;
  4452. result.y += this.y * scale;
  4453. result.z += this.z * scale;
  4454. result.w += this.w * scale;
  4455. return this;
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4459. */
  4460. Quaternion.prototype.multiply = function (q1) {
  4461. var result = new Quaternion(0, 0, 0, 1.0);
  4462. this.multiplyToRef(q1, result);
  4463. return result;
  4464. };
  4465. /**
  4466. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4467. * Returns the current Quaternion.
  4468. */
  4469. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4470. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4471. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4472. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4473. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4474. result.copyFromFloats(x, y, z, w);
  4475. return this;
  4476. };
  4477. /**
  4478. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4479. * Returns the updated Quaternion.
  4480. */
  4481. Quaternion.prototype.multiplyInPlace = function (q1) {
  4482. this.multiplyToRef(q1, this);
  4483. return this;
  4484. };
  4485. /**
  4486. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4487. * Returns the current Quaternion.
  4488. */
  4489. Quaternion.prototype.conjugateToRef = function (ref) {
  4490. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4491. return this;
  4492. };
  4493. /**
  4494. * Conjugates in place the current Quaternion.
  4495. * Returns the updated Quaternion.
  4496. */
  4497. Quaternion.prototype.conjugateInPlace = function () {
  4498. this.x *= -1;
  4499. this.y *= -1;
  4500. this.z *= -1;
  4501. return this;
  4502. };
  4503. /**
  4504. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4505. */
  4506. Quaternion.prototype.conjugate = function () {
  4507. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4508. return result;
  4509. };
  4510. /**
  4511. * Returns the Quaternion length (float).
  4512. */
  4513. Quaternion.prototype.length = function () {
  4514. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4515. };
  4516. /**
  4517. * Normalize in place the current Quaternion.
  4518. * Returns the updated Quaternion.
  4519. */
  4520. Quaternion.prototype.normalize = function () {
  4521. var length = 1.0 / this.length();
  4522. this.x *= length;
  4523. this.y *= length;
  4524. this.z *= length;
  4525. this.w *= length;
  4526. return this;
  4527. };
  4528. /**
  4529. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4530. * @param order is a reserved parameter and is ignore for now
  4531. * @returns the new Vector3
  4532. */
  4533. Quaternion.prototype.toEulerAngles = function (order) {
  4534. if (order === void 0) { order = "YZX"; }
  4535. var result = Vector3.Zero();
  4536. this.toEulerAnglesToRef(result, order);
  4537. return result;
  4538. };
  4539. /**
  4540. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4541. * @param result defines the vector which will be filled with the Euler angles
  4542. * @param order is a reserved parameter and is ignore for now
  4543. * @returns the current Quaternion
  4544. */
  4545. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4546. if (order === void 0) { order = "YZX"; }
  4547. var qz = this.z;
  4548. var qx = this.x;
  4549. var qy = this.y;
  4550. var qw = this.w;
  4551. var sqw = qw * qw;
  4552. var sqz = qz * qz;
  4553. var sqx = qx * qx;
  4554. var sqy = qy * qy;
  4555. var zAxisY = qy * qz - qx * qw;
  4556. var limit = .4999999;
  4557. if (zAxisY < -limit) {
  4558. result.y = 2 * Math.atan2(qy, qw);
  4559. result.x = Math.PI / 2;
  4560. result.z = 0;
  4561. }
  4562. else if (zAxisY > limit) {
  4563. result.y = 2 * Math.atan2(qy, qw);
  4564. result.x = -Math.PI / 2;
  4565. result.z = 0;
  4566. }
  4567. else {
  4568. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4569. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4570. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4571. }
  4572. return this;
  4573. };
  4574. /**
  4575. * Updates the passed rotation matrix with the current Quaternion values.
  4576. * Returns the current Quaternion.
  4577. */
  4578. Quaternion.prototype.toRotationMatrix = function (result) {
  4579. var xx = this.x * this.x;
  4580. var yy = this.y * this.y;
  4581. var zz = this.z * this.z;
  4582. var xy = this.x * this.y;
  4583. var zw = this.z * this.w;
  4584. var zx = this.z * this.x;
  4585. var yw = this.y * this.w;
  4586. var yz = this.y * this.z;
  4587. var xw = this.x * this.w;
  4588. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4589. result.m[1] = 2.0 * (xy + zw);
  4590. result.m[2] = 2.0 * (zx - yw);
  4591. result.m[3] = 0;
  4592. result.m[4] = 2.0 * (xy - zw);
  4593. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4594. result.m[6] = 2.0 * (yz + xw);
  4595. result.m[7] = 0;
  4596. result.m[8] = 2.0 * (zx + yw);
  4597. result.m[9] = 2.0 * (yz - xw);
  4598. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4599. result.m[11] = 0;
  4600. result.m[12] = 0;
  4601. result.m[13] = 0;
  4602. result.m[14] = 0;
  4603. result.m[15] = 1.0;
  4604. result._markAsUpdated();
  4605. return this;
  4606. };
  4607. /**
  4608. * Updates the current Quaternion from the passed rotation matrix values.
  4609. * Returns the updated Quaternion.
  4610. */
  4611. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4612. Quaternion.FromRotationMatrixToRef(matrix, this);
  4613. return this;
  4614. };
  4615. // Statics
  4616. /**
  4617. * Returns a new Quaternion set from the passed rotation matrix values.
  4618. */
  4619. Quaternion.FromRotationMatrix = function (matrix) {
  4620. var result = new Quaternion();
  4621. Quaternion.FromRotationMatrixToRef(matrix, result);
  4622. return result;
  4623. };
  4624. /**
  4625. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4626. */
  4627. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4628. var data = matrix.m;
  4629. var m11 = data[0], m12 = data[4], m13 = data[8];
  4630. var m21 = data[1], m22 = data[5], m23 = data[9];
  4631. var m31 = data[2], m32 = data[6], m33 = data[10];
  4632. var trace = m11 + m22 + m33;
  4633. var s;
  4634. if (trace > 0) {
  4635. s = 0.5 / Math.sqrt(trace + 1.0);
  4636. result.w = 0.25 / s;
  4637. result.x = (m32 - m23) * s;
  4638. result.y = (m13 - m31) * s;
  4639. result.z = (m21 - m12) * s;
  4640. }
  4641. else if (m11 > m22 && m11 > m33) {
  4642. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4643. result.w = (m32 - m23) / s;
  4644. result.x = 0.25 * s;
  4645. result.y = (m12 + m21) / s;
  4646. result.z = (m13 + m31) / s;
  4647. }
  4648. else if (m22 > m33) {
  4649. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4650. result.w = (m13 - m31) / s;
  4651. result.x = (m12 + m21) / s;
  4652. result.y = 0.25 * s;
  4653. result.z = (m23 + m32) / s;
  4654. }
  4655. else {
  4656. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4657. result.w = (m21 - m12) / s;
  4658. result.x = (m13 + m31) / s;
  4659. result.y = (m23 + m32) / s;
  4660. result.z = 0.25 * s;
  4661. }
  4662. };
  4663. /**
  4664. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4665. */
  4666. Quaternion.Zero = function () {
  4667. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4668. };
  4669. /**
  4670. * Returns a new Quaternion as the inverted current Quaternion.
  4671. */
  4672. Quaternion.Inverse = function (q) {
  4673. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4674. };
  4675. /**
  4676. * Returns the identity Quaternion.
  4677. */
  4678. Quaternion.Identity = function () {
  4679. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4680. };
  4681. Quaternion.IsIdentity = function (quaternion) {
  4682. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4683. };
  4684. /**
  4685. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4686. */
  4687. Quaternion.RotationAxis = function (axis, angle) {
  4688. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4689. };
  4690. /**
  4691. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4692. */
  4693. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4694. var sin = Math.sin(angle / 2);
  4695. axis.normalize();
  4696. result.w = Math.cos(angle / 2);
  4697. result.x = axis.x * sin;
  4698. result.y = axis.y * sin;
  4699. result.z = axis.z * sin;
  4700. return result;
  4701. };
  4702. /**
  4703. * Retuns a new Quaternion set from the starting index of the passed array.
  4704. */
  4705. Quaternion.FromArray = function (array, offset) {
  4706. if (!offset) {
  4707. offset = 0;
  4708. }
  4709. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4710. };
  4711. /**
  4712. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4713. */
  4714. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4715. var q = new Quaternion();
  4716. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4717. return q;
  4718. };
  4719. /**
  4720. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4721. */
  4722. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4723. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4724. var halfRoll = roll * 0.5;
  4725. var halfPitch = pitch * 0.5;
  4726. var halfYaw = yaw * 0.5;
  4727. var sinRoll = Math.sin(halfRoll);
  4728. var cosRoll = Math.cos(halfRoll);
  4729. var sinPitch = Math.sin(halfPitch);
  4730. var cosPitch = Math.cos(halfPitch);
  4731. var sinYaw = Math.sin(halfYaw);
  4732. var cosYaw = Math.cos(halfYaw);
  4733. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4734. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4735. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4736. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4737. };
  4738. /**
  4739. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4740. */
  4741. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4742. var result = new Quaternion();
  4743. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4748. */
  4749. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4750. // Produces a quaternion from Euler angles in the z-x-z orientation
  4751. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4752. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4753. var halfBeta = beta * 0.5;
  4754. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4755. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4756. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4757. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4758. };
  4759. /**
  4760. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4761. * cf to Vector3.RotationFromAxis() documentation.
  4762. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4763. */
  4764. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4765. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4766. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4767. return quat;
  4768. };
  4769. /**
  4770. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4771. * cf to Vector3.RotationFromAxis() documentation.
  4772. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4773. */
  4774. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4775. var rotMat = MathTmp.Matrix[0];
  4776. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4777. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4778. };
  4779. Quaternion.Slerp = function (left, right, amount) {
  4780. var result = Quaternion.Identity();
  4781. Quaternion.SlerpToRef(left, right, amount, result);
  4782. return result;
  4783. };
  4784. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4785. var num2;
  4786. var num3;
  4787. var num = amount;
  4788. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4789. var flag = false;
  4790. if (num4 < 0) {
  4791. flag = true;
  4792. num4 = -num4;
  4793. }
  4794. if (num4 > 0.999999) {
  4795. num3 = 1 - num;
  4796. num2 = flag ? -num : num;
  4797. }
  4798. else {
  4799. var num5 = Math.acos(num4);
  4800. var num6 = (1.0 / Math.sin(num5));
  4801. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4802. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4803. }
  4804. result.x = (num3 * left.x) + (num2 * right.x);
  4805. result.y = (num3 * left.y) + (num2 * right.y);
  4806. result.z = (num3 * left.z) + (num2 * right.z);
  4807. result.w = (num3 * left.w) + (num2 * right.w);
  4808. };
  4809. /**
  4810. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4811. */
  4812. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4813. var squared = amount * amount;
  4814. var cubed = amount * squared;
  4815. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4816. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4817. var part3 = (cubed - (2.0 * squared)) + amount;
  4818. var part4 = cubed - squared;
  4819. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4820. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4821. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4822. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4823. return new Quaternion(x, y, z, w);
  4824. };
  4825. return Quaternion;
  4826. }());
  4827. BABYLON.Quaternion = Quaternion;
  4828. var Matrix = /** @class */ (function () {
  4829. function Matrix() {
  4830. this._isIdentity = false;
  4831. this._isIdentityDirty = true;
  4832. this.m = new Float32Array(16);
  4833. this._markAsUpdated();
  4834. }
  4835. Matrix.prototype._markAsUpdated = function () {
  4836. this.updateFlag = Matrix._updateFlagSeed++;
  4837. this._isIdentityDirty = true;
  4838. };
  4839. // Properties
  4840. /**
  4841. * Boolean : True is the matrix is the identity matrix
  4842. */
  4843. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4844. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4845. if (this._isIdentityDirty) {
  4846. this._isIdentityDirty = false;
  4847. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4848. this._isIdentity = false;
  4849. }
  4850. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4851. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4852. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4853. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4854. this._isIdentity = false;
  4855. }
  4856. else {
  4857. this._isIdentity = true;
  4858. }
  4859. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4860. this._isIdentity = false;
  4861. }
  4862. }
  4863. return this._isIdentity;
  4864. };
  4865. /**
  4866. * Returns the matrix determinant (float).
  4867. */
  4868. Matrix.prototype.determinant = function () {
  4869. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4870. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4871. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4872. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4873. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4874. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4875. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4876. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4877. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4878. };
  4879. // Methods
  4880. /**
  4881. * Returns the matrix underlying array.
  4882. */
  4883. Matrix.prototype.toArray = function () {
  4884. return this.m;
  4885. };
  4886. /**
  4887. * Returns the matrix underlying array.
  4888. */
  4889. Matrix.prototype.asArray = function () {
  4890. return this.toArray();
  4891. };
  4892. /**
  4893. * Inverts in place the Matrix.
  4894. * Returns the Matrix inverted.
  4895. */
  4896. Matrix.prototype.invert = function () {
  4897. this.invertToRef(this);
  4898. return this;
  4899. };
  4900. /**
  4901. * Sets all the matrix elements to zero.
  4902. * Returns the Matrix.
  4903. */
  4904. Matrix.prototype.reset = function () {
  4905. for (var index = 0; index < 16; index++) {
  4906. this.m[index] = 0.0;
  4907. }
  4908. this._markAsUpdated();
  4909. return this;
  4910. };
  4911. /**
  4912. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4913. */
  4914. Matrix.prototype.add = function (other) {
  4915. var result = new Matrix();
  4916. this.addToRef(other, result);
  4917. return result;
  4918. };
  4919. /**
  4920. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4921. * Returns the Matrix.
  4922. */
  4923. Matrix.prototype.addToRef = function (other, result) {
  4924. for (var index = 0; index < 16; index++) {
  4925. result.m[index] = this.m[index] + other.m[index];
  4926. }
  4927. result._markAsUpdated();
  4928. return this;
  4929. };
  4930. /**
  4931. * Adds in place the passed matrix to the current Matrix.
  4932. * Returns the updated Matrix.
  4933. */
  4934. Matrix.prototype.addToSelf = function (other) {
  4935. for (var index = 0; index < 16; index++) {
  4936. this.m[index] += other.m[index];
  4937. }
  4938. this._markAsUpdated();
  4939. return this;
  4940. };
  4941. /**
  4942. * Sets the passed matrix with the current inverted Matrix.
  4943. * Returns the unmodified current Matrix.
  4944. */
  4945. Matrix.prototype.invertToRef = function (other) {
  4946. var l1 = this.m[0];
  4947. var l2 = this.m[1];
  4948. var l3 = this.m[2];
  4949. var l4 = this.m[3];
  4950. var l5 = this.m[4];
  4951. var l6 = this.m[5];
  4952. var l7 = this.m[6];
  4953. var l8 = this.m[7];
  4954. var l9 = this.m[8];
  4955. var l10 = this.m[9];
  4956. var l11 = this.m[10];
  4957. var l12 = this.m[11];
  4958. var l13 = this.m[12];
  4959. var l14 = this.m[13];
  4960. var l15 = this.m[14];
  4961. var l16 = this.m[15];
  4962. var l17 = (l11 * l16) - (l12 * l15);
  4963. var l18 = (l10 * l16) - (l12 * l14);
  4964. var l19 = (l10 * l15) - (l11 * l14);
  4965. var l20 = (l9 * l16) - (l12 * l13);
  4966. var l21 = (l9 * l15) - (l11 * l13);
  4967. var l22 = (l9 * l14) - (l10 * l13);
  4968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4973. var l28 = (l7 * l16) - (l8 * l15);
  4974. var l29 = (l6 * l16) - (l8 * l14);
  4975. var l30 = (l6 * l15) - (l7 * l14);
  4976. var l31 = (l5 * l16) - (l8 * l13);
  4977. var l32 = (l5 * l15) - (l7 * l13);
  4978. var l33 = (l5 * l14) - (l6 * l13);
  4979. var l34 = (l7 * l12) - (l8 * l11);
  4980. var l35 = (l6 * l12) - (l8 * l10);
  4981. var l36 = (l6 * l11) - (l7 * l10);
  4982. var l37 = (l5 * l12) - (l8 * l9);
  4983. var l38 = (l5 * l11) - (l7 * l9);
  4984. var l39 = (l5 * l10) - (l6 * l9);
  4985. other.m[0] = l23 * l27;
  4986. other.m[4] = l24 * l27;
  4987. other.m[8] = l25 * l27;
  4988. other.m[12] = l26 * l27;
  4989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5001. other._markAsUpdated();
  5002. return this;
  5003. };
  5004. /**
  5005. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5006. * Returns the updated Matrix.
  5007. */
  5008. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5009. this.m[12] = x;
  5010. this.m[13] = y;
  5011. this.m[14] = z;
  5012. this._markAsUpdated();
  5013. return this;
  5014. };
  5015. /**
  5016. * Inserts the translation vector in the current Matrix.
  5017. * Returns the updated Matrix.
  5018. */
  5019. Matrix.prototype.setTranslation = function (vector3) {
  5020. this.m[12] = vector3.x;
  5021. this.m[13] = vector3.y;
  5022. this.m[14] = vector3.z;
  5023. this._markAsUpdated();
  5024. return this;
  5025. };
  5026. /**
  5027. * Returns a new Vector3 as the extracted translation from the Matrix.
  5028. */
  5029. Matrix.prototype.getTranslation = function () {
  5030. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5031. };
  5032. /**
  5033. * Fill a Vector3 with the extracted translation from the Matrix.
  5034. */
  5035. Matrix.prototype.getTranslationToRef = function (result) {
  5036. result.x = this.m[12];
  5037. result.y = this.m[13];
  5038. result.z = this.m[14];
  5039. return this;
  5040. };
  5041. /**
  5042. * Remove rotation and scaling part from the Matrix.
  5043. * Returns the updated Matrix.
  5044. */
  5045. Matrix.prototype.removeRotationAndScaling = function () {
  5046. this.setRowFromFloats(0, 1, 0, 0, 0);
  5047. this.setRowFromFloats(1, 0, 1, 0, 0);
  5048. this.setRowFromFloats(2, 0, 0, 1, 0);
  5049. return this;
  5050. };
  5051. /**
  5052. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5053. */
  5054. Matrix.prototype.multiply = function (other) {
  5055. var result = new Matrix();
  5056. this.multiplyToRef(other, result);
  5057. return result;
  5058. };
  5059. /**
  5060. * Updates the current Matrix from the passed one values.
  5061. * Returns the updated Matrix.
  5062. */
  5063. Matrix.prototype.copyFrom = function (other) {
  5064. for (var index = 0; index < 16; index++) {
  5065. this.m[index] = other.m[index];
  5066. }
  5067. this._markAsUpdated();
  5068. return this;
  5069. };
  5070. /**
  5071. * Populates the passed array from the starting index with the Matrix values.
  5072. * Returns the Matrix.
  5073. */
  5074. Matrix.prototype.copyToArray = function (array, offset) {
  5075. if (offset === void 0) { offset = 0; }
  5076. for (var index = 0; index < 16; index++) {
  5077. array[offset + index] = this.m[index];
  5078. }
  5079. return this;
  5080. };
  5081. /**
  5082. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5083. */
  5084. Matrix.prototype.multiplyToRef = function (other, result) {
  5085. this.multiplyToArray(other, result.m, 0);
  5086. result._markAsUpdated();
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5091. */
  5092. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5093. var tm0 = this.m[0];
  5094. var tm1 = this.m[1];
  5095. var tm2 = this.m[2];
  5096. var tm3 = this.m[3];
  5097. var tm4 = this.m[4];
  5098. var tm5 = this.m[5];
  5099. var tm6 = this.m[6];
  5100. var tm7 = this.m[7];
  5101. var tm8 = this.m[8];
  5102. var tm9 = this.m[9];
  5103. var tm10 = this.m[10];
  5104. var tm11 = this.m[11];
  5105. var tm12 = this.m[12];
  5106. var tm13 = this.m[13];
  5107. var tm14 = this.m[14];
  5108. var tm15 = this.m[15];
  5109. var om0 = other.m[0];
  5110. var om1 = other.m[1];
  5111. var om2 = other.m[2];
  5112. var om3 = other.m[3];
  5113. var om4 = other.m[4];
  5114. var om5 = other.m[5];
  5115. var om6 = other.m[6];
  5116. var om7 = other.m[7];
  5117. var om8 = other.m[8];
  5118. var om9 = other.m[9];
  5119. var om10 = other.m[10];
  5120. var om11 = other.m[11];
  5121. var om12 = other.m[12];
  5122. var om13 = other.m[13];
  5123. var om14 = other.m[14];
  5124. var om15 = other.m[15];
  5125. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5126. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5127. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5128. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5129. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5130. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5131. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5132. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5133. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5134. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5135. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5136. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5137. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5138. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5139. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5140. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5141. return this;
  5142. };
  5143. /**
  5144. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5145. */
  5146. Matrix.prototype.equals = function (value) {
  5147. return value &&
  5148. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5149. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5150. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5151. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5152. };
  5153. /**
  5154. * Returns a new Matrix from the current Matrix.
  5155. */
  5156. Matrix.prototype.clone = function () {
  5157. 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]);
  5158. };
  5159. /**
  5160. * Returns the string "Matrix"
  5161. */
  5162. Matrix.prototype.getClassName = function () {
  5163. return "Matrix";
  5164. };
  5165. /**
  5166. * Returns the Matrix hash code.
  5167. */
  5168. Matrix.prototype.getHashCode = function () {
  5169. var hash = this.m[0] || 0;
  5170. for (var i = 1; i < 16; i++) {
  5171. hash = (hash * 397) ^ (this.m[i] || 0);
  5172. }
  5173. return hash;
  5174. };
  5175. /**
  5176. * Decomposes the current Matrix into :
  5177. * - a scale vector3 passed as a reference to update,
  5178. * - a rotation quaternion passed as a reference to update,
  5179. * - a translation vector3 passed as a reference to update.
  5180. * Returns the true if operation was successful.
  5181. */
  5182. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5183. translation.x = this.m[12];
  5184. translation.y = this.m[13];
  5185. translation.z = this.m[14];
  5186. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5187. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5188. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5189. if (this.determinant() <= 0) {
  5190. scale.y *= -1;
  5191. }
  5192. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5193. rotation.x = 0;
  5194. rotation.y = 0;
  5195. rotation.z = 0;
  5196. rotation.w = 1;
  5197. return false;
  5198. }
  5199. 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]);
  5200. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5201. return true;
  5202. };
  5203. /**
  5204. * Returns the index-th row of the current matrix as a new Vector4.
  5205. */
  5206. Matrix.prototype.getRow = function (index) {
  5207. if (index < 0 || index > 3) {
  5208. return null;
  5209. }
  5210. var i = index * 4;
  5211. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5212. };
  5213. /**
  5214. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5215. * Returns the updated Matrix.
  5216. */
  5217. Matrix.prototype.setRow = function (index, row) {
  5218. if (index < 0 || index > 3) {
  5219. return this;
  5220. }
  5221. var i = index * 4;
  5222. this.m[i + 0] = row.x;
  5223. this.m[i + 1] = row.y;
  5224. this.m[i + 2] = row.z;
  5225. this.m[i + 3] = row.w;
  5226. this._markAsUpdated();
  5227. return this;
  5228. };
  5229. /**
  5230. * Compute the transpose of the matrix.
  5231. * Returns a new Matrix.
  5232. */
  5233. Matrix.prototype.transpose = function () {
  5234. return Matrix.Transpose(this);
  5235. };
  5236. /**
  5237. * Compute the transpose of the matrix.
  5238. * Returns the current matrix.
  5239. */
  5240. Matrix.prototype.transposeToRef = function (result) {
  5241. Matrix.TransposeToRef(this, result);
  5242. return this;
  5243. };
  5244. /**
  5245. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5246. * Returns the updated Matrix.
  5247. */
  5248. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5249. if (index < 0 || index > 3) {
  5250. return this;
  5251. }
  5252. var i = index * 4;
  5253. this.m[i + 0] = x;
  5254. this.m[i + 1] = y;
  5255. this.m[i + 2] = z;
  5256. this.m[i + 3] = w;
  5257. this._markAsUpdated();
  5258. return this;
  5259. };
  5260. /**
  5261. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5262. * @param scale defines the scale factor
  5263. * @returns a new Matrix
  5264. */
  5265. Matrix.prototype.scale = function (scale) {
  5266. var result = new Matrix();
  5267. this.scaleToRef(scale, result);
  5268. return result;
  5269. };
  5270. /**
  5271. * Scale the current Matrix values by a factor to a given result Matrix
  5272. * @param scale defines the scale factor
  5273. * @param result defines the Matrix to store the result
  5274. * @returns the current Matrix
  5275. */
  5276. Matrix.prototype.scaleToRef = function (scale, result) {
  5277. for (var index = 0; index < 16; index++) {
  5278. result.m[index] = this.m[index] * scale;
  5279. }
  5280. result._markAsUpdated();
  5281. return this;
  5282. };
  5283. /**
  5284. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5285. * @param scale defines the scale factor
  5286. * @param result defines the Matrix to store the result
  5287. * @returns the current Matrix
  5288. */
  5289. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5290. for (var index = 0; index < 16; index++) {
  5291. result.m[index] += this.m[index] * scale;
  5292. }
  5293. result._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5298. * @param ref matrix to store the result
  5299. */
  5300. Matrix.prototype.toNormalMatrix = function (ref) {
  5301. this.invertToRef(ref);
  5302. ref.transpose();
  5303. var m = ref.m;
  5304. 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);
  5305. };
  5306. /**
  5307. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5308. */
  5309. Matrix.prototype.getRotationMatrix = function () {
  5310. var result = Matrix.Identity();
  5311. this.getRotationMatrixToRef(result);
  5312. return result;
  5313. };
  5314. /**
  5315. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5316. * Returns the current Matrix.
  5317. */
  5318. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5319. var m = this.m;
  5320. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5321. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5322. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5323. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5324. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5325. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5326. 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);
  5327. return this;
  5328. };
  5329. // Statics
  5330. /**
  5331. * Returns a new Matrix set from the starting index of the passed array.
  5332. */
  5333. Matrix.FromArray = function (array, offset) {
  5334. var result = new Matrix();
  5335. if (!offset) {
  5336. offset = 0;
  5337. }
  5338. Matrix.FromArrayToRef(array, offset, result);
  5339. return result;
  5340. };
  5341. /**
  5342. * Sets the passed "result" matrix from the starting index of the passed array.
  5343. */
  5344. Matrix.FromArrayToRef = function (array, offset, result) {
  5345. for (var index = 0; index < 16; index++) {
  5346. result.m[index] = array[index + offset];
  5347. }
  5348. result._markAsUpdated();
  5349. };
  5350. /**
  5351. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5352. */
  5353. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5354. for (var index = 0; index < 16; index++) {
  5355. result.m[index] = array[index + offset] * scale;
  5356. }
  5357. result._markAsUpdated();
  5358. };
  5359. /**
  5360. * Sets the passed matrix "result" with the 16 passed floats.
  5361. */
  5362. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5363. result.m[0] = initialM11;
  5364. result.m[1] = initialM12;
  5365. result.m[2] = initialM13;
  5366. result.m[3] = initialM14;
  5367. result.m[4] = initialM21;
  5368. result.m[5] = initialM22;
  5369. result.m[6] = initialM23;
  5370. result.m[7] = initialM24;
  5371. result.m[8] = initialM31;
  5372. result.m[9] = initialM32;
  5373. result.m[10] = initialM33;
  5374. result.m[11] = initialM34;
  5375. result.m[12] = initialM41;
  5376. result.m[13] = initialM42;
  5377. result.m[14] = initialM43;
  5378. result.m[15] = initialM44;
  5379. result._markAsUpdated();
  5380. };
  5381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5382. /**
  5383. * Static identity matrix to be used as readonly matrix
  5384. * Must not be updated.
  5385. */
  5386. get: function () {
  5387. return Matrix._identityReadOnly;
  5388. },
  5389. enumerable: true,
  5390. configurable: true
  5391. });
  5392. /**
  5393. * Returns a new Matrix set from the 16 passed floats.
  5394. */
  5395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5396. var result = new Matrix();
  5397. result.m[0] = initialM11;
  5398. result.m[1] = initialM12;
  5399. result.m[2] = initialM13;
  5400. result.m[3] = initialM14;
  5401. result.m[4] = initialM21;
  5402. result.m[5] = initialM22;
  5403. result.m[6] = initialM23;
  5404. result.m[7] = initialM24;
  5405. result.m[8] = initialM31;
  5406. result.m[9] = initialM32;
  5407. result.m[10] = initialM33;
  5408. result.m[11] = initialM34;
  5409. result.m[12] = initialM41;
  5410. result.m[13] = initialM42;
  5411. result.m[14] = initialM43;
  5412. result.m[15] = initialM44;
  5413. return result;
  5414. };
  5415. /**
  5416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5417. */
  5418. Matrix.Compose = function (scale, rotation, translation) {
  5419. var result = Matrix.Identity();
  5420. Matrix.ComposeToRef(scale, rotation, translation, result);
  5421. return result;
  5422. };
  5423. /**
  5424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5425. */
  5426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5430. result.setTranslation(translation);
  5431. };
  5432. /**
  5433. * Returns a new indentity Matrix.
  5434. */
  5435. Matrix.Identity = function () {
  5436. 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);
  5437. };
  5438. /**
  5439. * Sets the passed "result" as an identity matrix.
  5440. */
  5441. Matrix.IdentityToRef = function (result) {
  5442. 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);
  5443. };
  5444. /**
  5445. * Returns a new zero Matrix.
  5446. */
  5447. Matrix.Zero = function () {
  5448. 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);
  5449. };
  5450. /**
  5451. * Returns a new rotation matrix for "angle" radians around the X axis.
  5452. */
  5453. Matrix.RotationX = function (angle) {
  5454. var result = new Matrix();
  5455. Matrix.RotationXToRef(angle, result);
  5456. return result;
  5457. };
  5458. /**
  5459. * Returns a new Matrix as the passed inverted one.
  5460. */
  5461. Matrix.Invert = function (source) {
  5462. var result = new Matrix();
  5463. source.invertToRef(result);
  5464. return result;
  5465. };
  5466. /**
  5467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5468. */
  5469. Matrix.RotationXToRef = function (angle, result) {
  5470. var s = Math.sin(angle);
  5471. var c = Math.cos(angle);
  5472. result.m[0] = 1.0;
  5473. result.m[15] = 1.0;
  5474. result.m[5] = c;
  5475. result.m[10] = c;
  5476. result.m[9] = -s;
  5477. result.m[6] = s;
  5478. result.m[1] = 0.0;
  5479. result.m[2] = 0.0;
  5480. result.m[3] = 0.0;
  5481. result.m[4] = 0.0;
  5482. result.m[7] = 0.0;
  5483. result.m[8] = 0.0;
  5484. result.m[11] = 0.0;
  5485. result.m[12] = 0.0;
  5486. result.m[13] = 0.0;
  5487. result.m[14] = 0.0;
  5488. result._markAsUpdated();
  5489. };
  5490. /**
  5491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5492. */
  5493. Matrix.RotationY = function (angle) {
  5494. var result = new Matrix();
  5495. Matrix.RotationYToRef(angle, result);
  5496. return result;
  5497. };
  5498. /**
  5499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5500. */
  5501. Matrix.RotationYToRef = function (angle, result) {
  5502. var s = Math.sin(angle);
  5503. var c = Math.cos(angle);
  5504. result.m[5] = 1.0;
  5505. result.m[15] = 1.0;
  5506. result.m[0] = c;
  5507. result.m[2] = -s;
  5508. result.m[8] = s;
  5509. result.m[10] = c;
  5510. result.m[1] = 0.0;
  5511. result.m[3] = 0.0;
  5512. result.m[4] = 0.0;
  5513. result.m[6] = 0.0;
  5514. result.m[7] = 0.0;
  5515. result.m[9] = 0.0;
  5516. result.m[11] = 0.0;
  5517. result.m[12] = 0.0;
  5518. result.m[13] = 0.0;
  5519. result.m[14] = 0.0;
  5520. result._markAsUpdated();
  5521. };
  5522. /**
  5523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5524. */
  5525. Matrix.RotationZ = function (angle) {
  5526. var result = new Matrix();
  5527. Matrix.RotationZToRef(angle, result);
  5528. return result;
  5529. };
  5530. /**
  5531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5532. */
  5533. Matrix.RotationZToRef = function (angle, result) {
  5534. var s = Math.sin(angle);
  5535. var c = Math.cos(angle);
  5536. result.m[10] = 1.0;
  5537. result.m[15] = 1.0;
  5538. result.m[0] = c;
  5539. result.m[1] = s;
  5540. result.m[4] = -s;
  5541. result.m[5] = c;
  5542. result.m[2] = 0.0;
  5543. result.m[3] = 0.0;
  5544. result.m[6] = 0.0;
  5545. result.m[7] = 0.0;
  5546. result.m[8] = 0.0;
  5547. result.m[9] = 0.0;
  5548. result.m[11] = 0.0;
  5549. result.m[12] = 0.0;
  5550. result.m[13] = 0.0;
  5551. result.m[14] = 0.0;
  5552. result._markAsUpdated();
  5553. };
  5554. /**
  5555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5556. */
  5557. Matrix.RotationAxis = function (axis, angle) {
  5558. var result = Matrix.Zero();
  5559. Matrix.RotationAxisToRef(axis, angle, result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5564. */
  5565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5566. var s = Math.sin(-angle);
  5567. var c = Math.cos(-angle);
  5568. var c1 = 1 - c;
  5569. axis.normalize();
  5570. result.m[0] = (axis.x * axis.x) * c1 + c;
  5571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5573. result.m[3] = 0.0;
  5574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5575. result.m[5] = (axis.y * axis.y) * c1 + c;
  5576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5577. result.m[7] = 0.0;
  5578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5580. result.m[10] = (axis.z * axis.z) * c1 + c;
  5581. result.m[11] = 0.0;
  5582. result.m[15] = 1.0;
  5583. result._markAsUpdated();
  5584. };
  5585. /**
  5586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5587. */
  5588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5589. var result = new Matrix();
  5590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5591. return result;
  5592. };
  5593. /**
  5594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5595. */
  5596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5598. this._tempQuaternion.toRotationMatrix(result);
  5599. };
  5600. /**
  5601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5602. */
  5603. Matrix.Scaling = function (x, y, z) {
  5604. var result = Matrix.Zero();
  5605. Matrix.ScalingToRef(x, y, z, result);
  5606. return result;
  5607. };
  5608. /**
  5609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5610. */
  5611. Matrix.ScalingToRef = function (x, y, z, result) {
  5612. result.m[0] = x;
  5613. result.m[1] = 0.0;
  5614. result.m[2] = 0.0;
  5615. result.m[3] = 0.0;
  5616. result.m[4] = 0.0;
  5617. result.m[5] = y;
  5618. result.m[6] = 0.0;
  5619. result.m[7] = 0.0;
  5620. result.m[8] = 0.0;
  5621. result.m[9] = 0.0;
  5622. result.m[10] = z;
  5623. result.m[11] = 0.0;
  5624. result.m[12] = 0.0;
  5625. result.m[13] = 0.0;
  5626. result.m[14] = 0.0;
  5627. result.m[15] = 1.0;
  5628. result._markAsUpdated();
  5629. };
  5630. /**
  5631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5632. */
  5633. Matrix.Translation = function (x, y, z) {
  5634. var result = Matrix.Identity();
  5635. Matrix.TranslationToRef(x, y, z, result);
  5636. return result;
  5637. };
  5638. /**
  5639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5640. */
  5641. Matrix.TranslationToRef = function (x, y, z, result) {
  5642. 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);
  5643. };
  5644. /**
  5645. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5646. * @param startValue defines the start value
  5647. * @param endValue defines the end value
  5648. * @param gradient defines the gradient factor
  5649. * @returns the new matrix
  5650. */
  5651. Matrix.Lerp = function (startValue, endValue, gradient) {
  5652. var result = Matrix.Zero();
  5653. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5654. return result;
  5655. };
  5656. /**
  5657. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5658. * @param startValue defines the start value
  5659. * @param endValue defines the end value
  5660. * @param gradient defines the gradient factor
  5661. * @param result defines the Matrix object where to store data
  5662. */
  5663. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5664. for (var index = 0; index < 16; index++) {
  5665. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5666. }
  5667. result._markAsUpdated();
  5668. };
  5669. /**
  5670. * Returns a new Matrix whose values are computed by :
  5671. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5672. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5673. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5674. */
  5675. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5676. var startScale = new Vector3(0, 0, 0);
  5677. var startRotation = new Quaternion();
  5678. var startTranslation = new Vector3(0, 0, 0);
  5679. startValue.decompose(startScale, startRotation, startTranslation);
  5680. var endScale = new Vector3(0, 0, 0);
  5681. var endRotation = new Quaternion();
  5682. var endTranslation = new Vector3(0, 0, 0);
  5683. endValue.decompose(endScale, endRotation, endTranslation);
  5684. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5685. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5686. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5687. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5688. };
  5689. /**
  5690. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5691. * This methods works for a Left-Handed system.
  5692. */
  5693. Matrix.LookAtLH = function (eye, target, up) {
  5694. var result = Matrix.Zero();
  5695. Matrix.LookAtLHToRef(eye, target, up, result);
  5696. return result;
  5697. };
  5698. /**
  5699. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5700. * This methods works for a Left-Handed system.
  5701. */
  5702. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5703. // Z axis
  5704. target.subtractToRef(eye, this._zAxis);
  5705. this._zAxis.normalize();
  5706. // X axis
  5707. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5708. if (this._xAxis.lengthSquared() === 0) {
  5709. this._xAxis.x = 1.0;
  5710. }
  5711. else {
  5712. this._xAxis.normalize();
  5713. }
  5714. // Y axis
  5715. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5716. this._yAxis.normalize();
  5717. // Eye angles
  5718. var ex = -Vector3.Dot(this._xAxis, eye);
  5719. var ey = -Vector3.Dot(this._yAxis, eye);
  5720. var ez = -Vector3.Dot(this._zAxis, eye);
  5721. 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);
  5722. };
  5723. /**
  5724. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5725. * This methods works for a Right-Handed system.
  5726. */
  5727. Matrix.LookAtRH = function (eye, target, up) {
  5728. var result = Matrix.Zero();
  5729. Matrix.LookAtRHToRef(eye, target, up, result);
  5730. return result;
  5731. };
  5732. /**
  5733. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5734. * This methods works for a Left-Handed system.
  5735. */
  5736. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5737. // Z axis
  5738. eye.subtractToRef(target, this._zAxis);
  5739. this._zAxis.normalize();
  5740. // X axis
  5741. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5742. if (this._xAxis.lengthSquared() === 0) {
  5743. this._xAxis.x = 1.0;
  5744. }
  5745. else {
  5746. this._xAxis.normalize();
  5747. }
  5748. // Y axis
  5749. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5750. this._yAxis.normalize();
  5751. // Eye angles
  5752. var ex = -Vector3.Dot(this._xAxis, eye);
  5753. var ey = -Vector3.Dot(this._yAxis, eye);
  5754. var ez = -Vector3.Dot(this._zAxis, eye);
  5755. 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);
  5756. };
  5757. /**
  5758. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5759. */
  5760. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5761. var matrix = Matrix.Zero();
  5762. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5763. return matrix;
  5764. };
  5765. /**
  5766. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5767. */
  5768. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5769. var n = znear;
  5770. var f = zfar;
  5771. var a = 2.0 / width;
  5772. var b = 2.0 / height;
  5773. var c = 2.0 / (f - n);
  5774. var d = -(f + n) / (f - n);
  5775. 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);
  5776. };
  5777. /**
  5778. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5779. */
  5780. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5781. var matrix = Matrix.Zero();
  5782. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5783. return matrix;
  5784. };
  5785. /**
  5786. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5787. */
  5788. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5789. var n = znear;
  5790. var f = zfar;
  5791. var a = 2.0 / (right - left);
  5792. var b = 2.0 / (top - bottom);
  5793. var c = 2.0 / (f - n);
  5794. var d = -(f + n) / (f - n);
  5795. var i0 = (left + right) / (left - right);
  5796. var i1 = (top + bottom) / (bottom - top);
  5797. 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);
  5798. };
  5799. /**
  5800. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5801. */
  5802. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5803. var matrix = Matrix.Zero();
  5804. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5805. return matrix;
  5806. };
  5807. /**
  5808. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5809. */
  5810. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5811. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5812. result.m[10] *= -1.0;
  5813. };
  5814. /**
  5815. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5816. */
  5817. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5818. var matrix = Matrix.Zero();
  5819. var n = znear;
  5820. var f = zfar;
  5821. var a = 2.0 * n / width;
  5822. var b = 2.0 * n / height;
  5823. var c = (f + n) / (f - n);
  5824. var d = -2.0 * f * n / (f - n);
  5825. 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);
  5826. return matrix;
  5827. };
  5828. /**
  5829. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5830. */
  5831. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5832. var matrix = Matrix.Zero();
  5833. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5834. return matrix;
  5835. };
  5836. /**
  5837. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5838. */
  5839. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5840. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5841. var n = znear;
  5842. var f = zfar;
  5843. var t = 1.0 / (Math.tan(fov * 0.5));
  5844. var a = isVerticalFovFixed ? (t / aspect) : t;
  5845. var b = isVerticalFovFixed ? t : (t * aspect);
  5846. var c = (f + n) / (f - n);
  5847. var d = -2.0 * f * n / (f - n);
  5848. 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);
  5849. };
  5850. /**
  5851. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5852. */
  5853. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5854. var matrix = Matrix.Zero();
  5855. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5856. return matrix;
  5857. };
  5858. /**
  5859. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5860. */
  5861. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5862. //alternatively this could be expressed as:
  5863. // m = PerspectiveFovLHToRef
  5864. // m[10] *= -1.0;
  5865. // m[11] *= -1.0;
  5866. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5867. var n = znear;
  5868. var f = zfar;
  5869. var t = 1.0 / (Math.tan(fov * 0.5));
  5870. var a = isVerticalFovFixed ? (t / aspect) : t;
  5871. var b = isVerticalFovFixed ? t : (t * aspect);
  5872. var c = -(f + n) / (f - n);
  5873. var d = -2 * f * n / (f - n);
  5874. 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);
  5875. };
  5876. /**
  5877. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5878. */
  5879. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5880. if (rightHanded === void 0) { rightHanded = false; }
  5881. var rightHandedFactor = rightHanded ? -1 : 1;
  5882. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5883. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5884. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5885. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5886. var xScale = 2.0 / (leftTan + rightTan);
  5887. var yScale = 2.0 / (upTan + downTan);
  5888. result.m[0] = xScale;
  5889. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5890. result.m[5] = yScale;
  5891. result.m[6] = result.m[7] = 0.0;
  5892. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5893. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5894. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5895. result.m[10] = -zfar / (znear - zfar);
  5896. result.m[11] = 1.0 * rightHandedFactor;
  5897. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5898. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5899. // result.m[14] = (znear * zfar) / (znear - zfar);
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Returns the final transformation matrix : world * view * projection * viewport
  5904. */
  5905. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5906. var cw = viewport.width;
  5907. var ch = viewport.height;
  5908. var cx = viewport.x;
  5909. var cy = viewport.y;
  5910. 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);
  5911. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5912. };
  5913. /**
  5914. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5915. */
  5916. Matrix.GetAsMatrix2x2 = function (matrix) {
  5917. return new Float32Array([
  5918. matrix.m[0], matrix.m[1],
  5919. matrix.m[4], matrix.m[5]
  5920. ]);
  5921. };
  5922. /**
  5923. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5924. */
  5925. Matrix.GetAsMatrix3x3 = function (matrix) {
  5926. return new Float32Array([
  5927. matrix.m[0], matrix.m[1], matrix.m[2],
  5928. matrix.m[4], matrix.m[5], matrix.m[6],
  5929. matrix.m[8], matrix.m[9], matrix.m[10]
  5930. ]);
  5931. };
  5932. /**
  5933. * Compute the transpose of the passed Matrix.
  5934. * Returns a new Matrix.
  5935. */
  5936. Matrix.Transpose = function (matrix) {
  5937. var result = new Matrix();
  5938. Matrix.TransposeToRef(matrix, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5943. */
  5944. Matrix.TransposeToRef = function (matrix, result) {
  5945. result.m[0] = matrix.m[0];
  5946. result.m[1] = matrix.m[4];
  5947. result.m[2] = matrix.m[8];
  5948. result.m[3] = matrix.m[12];
  5949. result.m[4] = matrix.m[1];
  5950. result.m[5] = matrix.m[5];
  5951. result.m[6] = matrix.m[9];
  5952. result.m[7] = matrix.m[13];
  5953. result.m[8] = matrix.m[2];
  5954. result.m[9] = matrix.m[6];
  5955. result.m[10] = matrix.m[10];
  5956. result.m[11] = matrix.m[14];
  5957. result.m[12] = matrix.m[3];
  5958. result.m[13] = matrix.m[7];
  5959. result.m[14] = matrix.m[11];
  5960. result.m[15] = matrix.m[15];
  5961. };
  5962. /**
  5963. * Returns a new Matrix as the reflection matrix across the passed plane.
  5964. */
  5965. Matrix.Reflection = function (plane) {
  5966. var matrix = new Matrix();
  5967. Matrix.ReflectionToRef(plane, matrix);
  5968. return matrix;
  5969. };
  5970. /**
  5971. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5972. */
  5973. Matrix.ReflectionToRef = function (plane, result) {
  5974. plane.normalize();
  5975. var x = plane.normal.x;
  5976. var y = plane.normal.y;
  5977. var z = plane.normal.z;
  5978. var temp = -2 * x;
  5979. var temp2 = -2 * y;
  5980. var temp3 = -2 * z;
  5981. result.m[0] = (temp * x) + 1;
  5982. result.m[1] = temp2 * x;
  5983. result.m[2] = temp3 * x;
  5984. result.m[3] = 0.0;
  5985. result.m[4] = temp * y;
  5986. result.m[5] = (temp2 * y) + 1;
  5987. result.m[6] = temp3 * y;
  5988. result.m[7] = 0.0;
  5989. result.m[8] = temp * z;
  5990. result.m[9] = temp2 * z;
  5991. result.m[10] = (temp3 * z) + 1;
  5992. result.m[11] = 0.0;
  5993. result.m[12] = temp * plane.d;
  5994. result.m[13] = temp2 * plane.d;
  5995. result.m[14] = temp3 * plane.d;
  5996. result.m[15] = 1.0;
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6001. */
  6002. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6003. result.m[0] = xaxis.x;
  6004. result.m[1] = xaxis.y;
  6005. result.m[2] = xaxis.z;
  6006. result.m[3] = 0.0;
  6007. result.m[4] = yaxis.x;
  6008. result.m[5] = yaxis.y;
  6009. result.m[6] = yaxis.z;
  6010. result.m[7] = 0.0;
  6011. result.m[8] = zaxis.x;
  6012. result.m[9] = zaxis.y;
  6013. result.m[10] = zaxis.z;
  6014. result.m[11] = 0.0;
  6015. result.m[12] = 0.0;
  6016. result.m[13] = 0.0;
  6017. result.m[14] = 0.0;
  6018. result.m[15] = 1.0;
  6019. result._markAsUpdated();
  6020. };
  6021. /**
  6022. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6023. */
  6024. Matrix.FromQuaternionToRef = function (quat, result) {
  6025. var xx = quat.x * quat.x;
  6026. var yy = quat.y * quat.y;
  6027. var zz = quat.z * quat.z;
  6028. var xy = quat.x * quat.y;
  6029. var zw = quat.z * quat.w;
  6030. var zx = quat.z * quat.x;
  6031. var yw = quat.y * quat.w;
  6032. var yz = quat.y * quat.z;
  6033. var xw = quat.x * quat.w;
  6034. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6035. result.m[1] = 2.0 * (xy + zw);
  6036. result.m[2] = 2.0 * (zx - yw);
  6037. result.m[3] = 0.0;
  6038. result.m[4] = 2.0 * (xy - zw);
  6039. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6040. result.m[6] = 2.0 * (yz + xw);
  6041. result.m[7] = 0.0;
  6042. result.m[8] = 2.0 * (zx + yw);
  6043. result.m[9] = 2.0 * (yz - xw);
  6044. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6045. result.m[11] = 0.0;
  6046. result.m[12] = 0.0;
  6047. result.m[13] = 0.0;
  6048. result.m[14] = 0.0;
  6049. result.m[15] = 1.0;
  6050. result._markAsUpdated();
  6051. };
  6052. Matrix._tempQuaternion = new Quaternion();
  6053. Matrix._xAxis = Vector3.Zero();
  6054. Matrix._yAxis = Vector3.Zero();
  6055. Matrix._zAxis = Vector3.Zero();
  6056. Matrix._updateFlagSeed = 0;
  6057. Matrix._identityReadOnly = Matrix.Identity();
  6058. return Matrix;
  6059. }());
  6060. BABYLON.Matrix = Matrix;
  6061. var Plane = /** @class */ (function () {
  6062. /**
  6063. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6064. */
  6065. function Plane(a, b, c, d) {
  6066. this.normal = new Vector3(a, b, c);
  6067. this.d = d;
  6068. }
  6069. /**
  6070. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6071. */
  6072. Plane.prototype.asArray = function () {
  6073. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6074. };
  6075. // Methods
  6076. /**
  6077. * Returns a new plane copied from the current Plane.
  6078. */
  6079. Plane.prototype.clone = function () {
  6080. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6081. };
  6082. /**
  6083. * Returns the string "Plane".
  6084. */
  6085. Plane.prototype.getClassName = function () {
  6086. return "Plane";
  6087. };
  6088. /**
  6089. * Returns the Plane hash code.
  6090. */
  6091. Plane.prototype.getHashCode = function () {
  6092. var hash = this.normal.getHashCode();
  6093. hash = (hash * 397) ^ (this.d || 0);
  6094. return hash;
  6095. };
  6096. /**
  6097. * Normalize the current Plane in place.
  6098. * Returns the updated Plane.
  6099. */
  6100. Plane.prototype.normalize = function () {
  6101. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6102. var magnitude = 0.0;
  6103. if (norm !== 0) {
  6104. magnitude = 1.0 / norm;
  6105. }
  6106. this.normal.x *= magnitude;
  6107. this.normal.y *= magnitude;
  6108. this.normal.z *= magnitude;
  6109. this.d *= magnitude;
  6110. return this;
  6111. };
  6112. /**
  6113. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6114. */
  6115. Plane.prototype.transform = function (transformation) {
  6116. var transposedMatrix = Matrix.Transpose(transformation);
  6117. var x = this.normal.x;
  6118. var y = this.normal.y;
  6119. var z = this.normal.z;
  6120. var d = this.d;
  6121. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6122. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6123. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6124. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6125. return new Plane(normalX, normalY, normalZ, finalD);
  6126. };
  6127. /**
  6128. * Returns the dot product (float) of the point coordinates and the plane normal.
  6129. */
  6130. Plane.prototype.dotCoordinate = function (point) {
  6131. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6132. };
  6133. /**
  6134. * Updates the current Plane from the plane defined by the three passed points.
  6135. * Returns the updated Plane.
  6136. */
  6137. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6138. var x1 = point2.x - point1.x;
  6139. var y1 = point2.y - point1.y;
  6140. var z1 = point2.z - point1.z;
  6141. var x2 = point3.x - point1.x;
  6142. var y2 = point3.y - point1.y;
  6143. var z2 = point3.z - point1.z;
  6144. var yz = (y1 * z2) - (z1 * y2);
  6145. var xz = (z1 * x2) - (x1 * z2);
  6146. var xy = (x1 * y2) - (y1 * x2);
  6147. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6148. var invPyth;
  6149. if (pyth !== 0) {
  6150. invPyth = 1.0 / pyth;
  6151. }
  6152. else {
  6153. invPyth = 0.0;
  6154. }
  6155. this.normal.x = yz * invPyth;
  6156. this.normal.y = xz * invPyth;
  6157. this.normal.z = xy * invPyth;
  6158. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6159. return this;
  6160. };
  6161. /**
  6162. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6163. */
  6164. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6165. var dot = Vector3.Dot(this.normal, direction);
  6166. return (dot <= epsilon);
  6167. };
  6168. /**
  6169. * Returns the signed distance (float) from the passed point to the Plane.
  6170. */
  6171. Plane.prototype.signedDistanceTo = function (point) {
  6172. return Vector3.Dot(point, this.normal) + this.d;
  6173. };
  6174. // Statics
  6175. /**
  6176. * Returns a new Plane from the passed array.
  6177. */
  6178. Plane.FromArray = function (array) {
  6179. return new Plane(array[0], array[1], array[2], array[3]);
  6180. };
  6181. /**
  6182. * Returns a new Plane defined by the three passed points.
  6183. */
  6184. Plane.FromPoints = function (point1, point2, point3) {
  6185. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6186. result.copyFromPoints(point1, point2, point3);
  6187. return result;
  6188. };
  6189. /**
  6190. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6191. * Note : the vector "normal" is updated because normalized.
  6192. */
  6193. Plane.FromPositionAndNormal = function (origin, normal) {
  6194. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6195. normal.normalize();
  6196. result.normal = normal;
  6197. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6198. return result;
  6199. };
  6200. /**
  6201. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6202. */
  6203. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6204. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6205. return Vector3.Dot(point, normal) + d;
  6206. };
  6207. return Plane;
  6208. }());
  6209. BABYLON.Plane = Plane;
  6210. var Viewport = /** @class */ (function () {
  6211. /**
  6212. * Creates a Viewport object located at (x, y) and sized (width, height).
  6213. */
  6214. function Viewport(x, y, width, height) {
  6215. this.x = x;
  6216. this.y = y;
  6217. this.width = width;
  6218. this.height = height;
  6219. }
  6220. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6221. if (renderWidthOrEngine.getRenderWidth) {
  6222. var engine = renderWidthOrEngine;
  6223. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6224. }
  6225. var renderWidth = renderWidthOrEngine;
  6226. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6227. };
  6228. /**
  6229. * Returns a new Viewport copied from the current one.
  6230. */
  6231. Viewport.prototype.clone = function () {
  6232. return new Viewport(this.x, this.y, this.width, this.height);
  6233. };
  6234. return Viewport;
  6235. }());
  6236. BABYLON.Viewport = Viewport;
  6237. var Frustum = /** @class */ (function () {
  6238. function Frustum() {
  6239. }
  6240. /**
  6241. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6242. */
  6243. Frustum.GetPlanes = function (transform) {
  6244. var frustumPlanes = [];
  6245. for (var index = 0; index < 6; index++) {
  6246. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6247. }
  6248. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6249. return frustumPlanes;
  6250. };
  6251. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6252. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6253. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6254. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6255. frustumPlane.d = transform.m[15] + transform.m[14];
  6256. frustumPlane.normalize();
  6257. };
  6258. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6259. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6260. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6261. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6262. frustumPlane.d = transform.m[15] - transform.m[14];
  6263. frustumPlane.normalize();
  6264. };
  6265. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6266. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6267. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6268. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6269. frustumPlane.d = transform.m[15] + transform.m[12];
  6270. frustumPlane.normalize();
  6271. };
  6272. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6273. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6274. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6275. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6276. frustumPlane.d = transform.m[15] - transform.m[12];
  6277. frustumPlane.normalize();
  6278. };
  6279. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6280. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6281. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6282. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6283. frustumPlane.d = transform.m[15] - transform.m[13];
  6284. frustumPlane.normalize();
  6285. };
  6286. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6287. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6288. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6289. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6290. frustumPlane.d = transform.m[15] + transform.m[13];
  6291. frustumPlane.normalize();
  6292. };
  6293. /**
  6294. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6295. */
  6296. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6297. // Near
  6298. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6299. // Far
  6300. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6301. // Left
  6302. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6303. // Right
  6304. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6305. // Top
  6306. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6307. // Bottom
  6308. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6309. };
  6310. return Frustum;
  6311. }());
  6312. BABYLON.Frustum = Frustum;
  6313. var Space;
  6314. (function (Space) {
  6315. Space[Space["LOCAL"] = 0] = "LOCAL";
  6316. Space[Space["WORLD"] = 1] = "WORLD";
  6317. Space[Space["BONE"] = 2] = "BONE";
  6318. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6319. var Axis = /** @class */ (function () {
  6320. function Axis() {
  6321. }
  6322. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6323. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6324. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6325. return Axis;
  6326. }());
  6327. BABYLON.Axis = Axis;
  6328. ;
  6329. var BezierCurve = /** @class */ (function () {
  6330. function BezierCurve() {
  6331. }
  6332. /**
  6333. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6334. */
  6335. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6336. // Extract X (which is equal to time here)
  6337. var f0 = 1 - 3 * x2 + 3 * x1;
  6338. var f1 = 3 * x2 - 6 * x1;
  6339. var f2 = 3 * x1;
  6340. var refinedT = t;
  6341. for (var i = 0; i < 5; i++) {
  6342. var refinedT2 = refinedT * refinedT;
  6343. var refinedT3 = refinedT2 * refinedT;
  6344. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6345. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6346. refinedT -= (x - t) * slope;
  6347. refinedT = Math.min(1, Math.max(0, refinedT));
  6348. }
  6349. // Resolve cubic bezier for the given x
  6350. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6351. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6352. Math.pow(refinedT, 3);
  6353. };
  6354. return BezierCurve;
  6355. }());
  6356. BABYLON.BezierCurve = BezierCurve;
  6357. var Orientation;
  6358. (function (Orientation) {
  6359. Orientation[Orientation["CW"] = 0] = "CW";
  6360. Orientation[Orientation["CCW"] = 1] = "CCW";
  6361. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6362. var Angle = /** @class */ (function () {
  6363. /**
  6364. * Creates an Angle object of "radians" radians (float).
  6365. */
  6366. function Angle(radians) {
  6367. var _this = this;
  6368. /**
  6369. * Returns the Angle value in degrees (float).
  6370. */
  6371. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6372. /**
  6373. * Returns the Angle value in radians (float).
  6374. */
  6375. this.radians = function () { return _this._radians; };
  6376. this._radians = radians;
  6377. if (this._radians < 0.0)
  6378. this._radians += (2.0 * Math.PI);
  6379. }
  6380. /**
  6381. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6382. */
  6383. Angle.BetweenTwoPoints = function (a, b) {
  6384. var delta = b.subtract(a);
  6385. var theta = Math.atan2(delta.y, delta.x);
  6386. return new Angle(theta);
  6387. };
  6388. /**
  6389. * Returns a new Angle object from the passed float in radians.
  6390. */
  6391. Angle.FromRadians = function (radians) {
  6392. return new Angle(radians);
  6393. };
  6394. /**
  6395. * Returns a new Angle object from the passed float in degrees.
  6396. */
  6397. Angle.FromDegrees = function (degrees) {
  6398. return new Angle(degrees * Math.PI / 180.0);
  6399. };
  6400. return Angle;
  6401. }());
  6402. BABYLON.Angle = Angle;
  6403. var Arc2 = /** @class */ (function () {
  6404. /**
  6405. * Creates an Arc object from the three passed points : start, middle and end.
  6406. */
  6407. function Arc2(startPoint, midPoint, endPoint) {
  6408. this.startPoint = startPoint;
  6409. this.midPoint = midPoint;
  6410. this.endPoint = endPoint;
  6411. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6412. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6413. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6414. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6415. 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);
  6416. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6417. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6418. var a1 = this.startAngle.degrees();
  6419. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6420. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6421. // angles correction
  6422. if (a2 - a1 > +180.0)
  6423. a2 -= 360.0;
  6424. if (a2 - a1 < -180.0)
  6425. a2 += 360.0;
  6426. if (a3 - a2 > +180.0)
  6427. a3 -= 360.0;
  6428. if (a3 - a2 < -180.0)
  6429. a3 += 360.0;
  6430. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6431. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6432. }
  6433. return Arc2;
  6434. }());
  6435. BABYLON.Arc2 = Arc2;
  6436. var Path2 = /** @class */ (function () {
  6437. /**
  6438. * Creates a Path2 object from the starting 2D coordinates x and y.
  6439. */
  6440. function Path2(x, y) {
  6441. this._points = new Array();
  6442. this._length = 0.0;
  6443. this.closed = false;
  6444. this._points.push(new Vector2(x, y));
  6445. }
  6446. /**
  6447. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6448. * Returns the updated Path2.
  6449. */
  6450. Path2.prototype.addLineTo = function (x, y) {
  6451. if (this.closed) {
  6452. return this;
  6453. }
  6454. var newPoint = new Vector2(x, y);
  6455. var previousPoint = this._points[this._points.length - 1];
  6456. this._points.push(newPoint);
  6457. this._length += newPoint.subtract(previousPoint).length();
  6458. return this;
  6459. };
  6460. /**
  6461. * 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.
  6462. * Returns the updated Path2.
  6463. */
  6464. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6465. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6466. if (this.closed) {
  6467. return this;
  6468. }
  6469. var startPoint = this._points[this._points.length - 1];
  6470. var midPoint = new Vector2(midX, midY);
  6471. var endPoint = new Vector2(endX, endY);
  6472. var arc = new Arc2(startPoint, midPoint, endPoint);
  6473. var increment = arc.angle.radians() / numberOfSegments;
  6474. if (arc.orientation === Orientation.CW)
  6475. increment *= -1;
  6476. var currentAngle = arc.startAngle.radians() + increment;
  6477. for (var i = 0; i < numberOfSegments; i++) {
  6478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6480. this.addLineTo(x, y);
  6481. currentAngle += increment;
  6482. }
  6483. return this;
  6484. };
  6485. /**
  6486. * Closes the Path2.
  6487. * Returns the Path2.
  6488. */
  6489. Path2.prototype.close = function () {
  6490. this.closed = true;
  6491. return this;
  6492. };
  6493. /**
  6494. * Returns the Path2 total length (float).
  6495. */
  6496. Path2.prototype.length = function () {
  6497. var result = this._length;
  6498. if (!this.closed) {
  6499. var lastPoint = this._points[this._points.length - 1];
  6500. var firstPoint = this._points[0];
  6501. result += (firstPoint.subtract(lastPoint).length());
  6502. }
  6503. return result;
  6504. };
  6505. /**
  6506. * Returns the Path2 internal array of points.
  6507. */
  6508. Path2.prototype.getPoints = function () {
  6509. return this._points;
  6510. };
  6511. /**
  6512. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6513. */
  6514. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6515. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6516. return Vector2.Zero();
  6517. }
  6518. var lengthPosition = normalizedLengthPosition * this.length();
  6519. var previousOffset = 0;
  6520. for (var i = 0; i < this._points.length; i++) {
  6521. var j = (i + 1) % this._points.length;
  6522. var a = this._points[i];
  6523. var b = this._points[j];
  6524. var bToA = b.subtract(a);
  6525. var nextOffset = (bToA.length() + previousOffset);
  6526. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6527. var dir = bToA.normalize();
  6528. var localOffset = lengthPosition - previousOffset;
  6529. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6530. }
  6531. previousOffset = nextOffset;
  6532. }
  6533. return Vector2.Zero();
  6534. };
  6535. /**
  6536. * Returns a new Path2 starting at the coordinates (x, y).
  6537. */
  6538. Path2.StartingAt = function (x, y) {
  6539. return new Path2(x, y);
  6540. };
  6541. return Path2;
  6542. }());
  6543. BABYLON.Path2 = Path2;
  6544. var Path3D = /** @class */ (function () {
  6545. /**
  6546. * new Path3D(path, normal, raw)
  6547. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6548. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6549. * path : an array of Vector3, the curve axis of the Path3D
  6550. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6551. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6552. */
  6553. function Path3D(path, firstNormal, raw) {
  6554. if (firstNormal === void 0) { firstNormal = null; }
  6555. this.path = path;
  6556. this._curve = new Array();
  6557. this._distances = new Array();
  6558. this._tangents = new Array();
  6559. this._normals = new Array();
  6560. this._binormals = new Array();
  6561. for (var p = 0; p < path.length; p++) {
  6562. this._curve[p] = path[p].clone(); // hard copy
  6563. }
  6564. this._raw = raw || false;
  6565. this._compute(firstNormal);
  6566. }
  6567. /**
  6568. * Returns the Path3D array of successive Vector3 designing its curve.
  6569. */
  6570. Path3D.prototype.getCurve = function () {
  6571. return this._curve;
  6572. };
  6573. /**
  6574. * Returns an array populated with tangent vectors on each Path3D curve point.
  6575. */
  6576. Path3D.prototype.getTangents = function () {
  6577. return this._tangents;
  6578. };
  6579. /**
  6580. * Returns an array populated with normal vectors on each Path3D curve point.
  6581. */
  6582. Path3D.prototype.getNormals = function () {
  6583. return this._normals;
  6584. };
  6585. /**
  6586. * Returns an array populated with binormal vectors on each Path3D curve point.
  6587. */
  6588. Path3D.prototype.getBinormals = function () {
  6589. return this._binormals;
  6590. };
  6591. /**
  6592. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6593. */
  6594. Path3D.prototype.getDistances = function () {
  6595. return this._distances;
  6596. };
  6597. /**
  6598. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6599. * Returns the same object updated.
  6600. */
  6601. Path3D.prototype.update = function (path, firstNormal) {
  6602. if (firstNormal === void 0) { firstNormal = null; }
  6603. for (var p = 0; p < path.length; p++) {
  6604. this._curve[p].x = path[p].x;
  6605. this._curve[p].y = path[p].y;
  6606. this._curve[p].z = path[p].z;
  6607. }
  6608. this._compute(firstNormal);
  6609. return this;
  6610. };
  6611. // private function compute() : computes tangents, normals and binormals
  6612. Path3D.prototype._compute = function (firstNormal) {
  6613. var l = this._curve.length;
  6614. // first and last tangents
  6615. this._tangents[0] = this._getFirstNonNullVector(0);
  6616. if (!this._raw) {
  6617. this._tangents[0].normalize();
  6618. }
  6619. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6620. if (!this._raw) {
  6621. this._tangents[l - 1].normalize();
  6622. }
  6623. // normals and binormals at first point : arbitrary vector with _normalVector()
  6624. var tg0 = this._tangents[0];
  6625. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6626. this._normals[0] = pp0;
  6627. if (!this._raw) {
  6628. this._normals[0].normalize();
  6629. }
  6630. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6631. if (!this._raw) {
  6632. this._binormals[0].normalize();
  6633. }
  6634. this._distances[0] = 0.0;
  6635. // normals and binormals : next points
  6636. var prev; // previous vector (segment)
  6637. var cur; // current vector (segment)
  6638. var curTang; // current tangent
  6639. // previous normal
  6640. var prevBinor; // previous binormal
  6641. for (var i = 1; i < l; i++) {
  6642. // tangents
  6643. prev = this._getLastNonNullVector(i);
  6644. if (i < l - 1) {
  6645. cur = this._getFirstNonNullVector(i);
  6646. this._tangents[i] = prev.add(cur);
  6647. this._tangents[i].normalize();
  6648. }
  6649. this._distances[i] = this._distances[i - 1] + prev.length();
  6650. // normals and binormals
  6651. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6652. curTang = this._tangents[i];
  6653. prevBinor = this._binormals[i - 1];
  6654. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6655. if (!this._raw) {
  6656. this._normals[i].normalize();
  6657. }
  6658. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6659. if (!this._raw) {
  6660. this._binormals[i].normalize();
  6661. }
  6662. }
  6663. };
  6664. // private function getFirstNonNullVector(index)
  6665. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6666. Path3D.prototype._getFirstNonNullVector = function (index) {
  6667. var i = 1;
  6668. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6669. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6670. i++;
  6671. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6672. }
  6673. return nNVector;
  6674. };
  6675. // private function getLastNonNullVector(index)
  6676. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6677. Path3D.prototype._getLastNonNullVector = function (index) {
  6678. var i = 1;
  6679. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6680. while (nLVector.length() === 0 && index > i + 1) {
  6681. i++;
  6682. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6683. }
  6684. return nLVector;
  6685. };
  6686. // private function normalVector(v0, vt, va) :
  6687. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6688. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6689. Path3D.prototype._normalVector = function (v0, vt, va) {
  6690. var normal0;
  6691. var tgl = vt.length();
  6692. if (tgl === 0.0) {
  6693. tgl = 1.0;
  6694. }
  6695. if (va === undefined || va === null) {
  6696. var point;
  6697. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6698. point = new Vector3(0.0, -1.0, 0.0);
  6699. }
  6700. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6701. point = new Vector3(1.0, 0.0, 0.0);
  6702. }
  6703. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6704. point = new Vector3(0.0, 0.0, 1.0);
  6705. }
  6706. else {
  6707. point = Vector3.Zero();
  6708. }
  6709. normal0 = Vector3.Cross(vt, point);
  6710. }
  6711. else {
  6712. normal0 = Vector3.Cross(vt, va);
  6713. Vector3.CrossToRef(normal0, vt, normal0);
  6714. }
  6715. normal0.normalize();
  6716. return normal0;
  6717. };
  6718. return Path3D;
  6719. }());
  6720. BABYLON.Path3D = Path3D;
  6721. var Curve3 = /** @class */ (function () {
  6722. /**
  6723. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6724. * A Curve3 is designed from a series of successive Vector3.
  6725. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6726. */
  6727. function Curve3(points) {
  6728. this._length = 0.0;
  6729. this._points = points;
  6730. this._length = this._computeLength(points);
  6731. }
  6732. /**
  6733. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6734. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6735. * @param v1 (Vector3) the control point
  6736. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6737. * @param nbPoints (integer) the wanted number of points in the curve
  6738. */
  6739. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6740. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6741. var bez = new Array();
  6742. var equation = function (t, val0, val1, val2) {
  6743. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6744. return res;
  6745. };
  6746. for (var i = 0; i <= nbPoints; i++) {
  6747. 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)));
  6748. }
  6749. return new Curve3(bez);
  6750. };
  6751. /**
  6752. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6753. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6754. * @param v1 (Vector3) the first control point
  6755. * @param v2 (Vector3) the second control point
  6756. * @param v3 (Vector3) the end point of the Cubic Bezier
  6757. * @param nbPoints (integer) the wanted number of points in the curve
  6758. */
  6759. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6760. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6761. var bez = new Array();
  6762. var equation = function (t, val0, val1, val2, val3) {
  6763. 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;
  6764. return res;
  6765. };
  6766. for (var i = 0; i <= nbPoints; i++) {
  6767. 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)));
  6768. }
  6769. return new Curve3(bez);
  6770. };
  6771. /**
  6772. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6773. * @param p1 (Vector3) the origin point of the Hermite Spline
  6774. * @param t1 (Vector3) the tangent vector at the origin point
  6775. * @param p2 (Vector3) the end point of the Hermite Spline
  6776. * @param t2 (Vector3) the tangent vector at the end point
  6777. * @param nbPoints (integer) the wanted number of points in the curve
  6778. */
  6779. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6780. var hermite = new Array();
  6781. var step = 1.0 / nbPoints;
  6782. for (var i = 0; i <= nbPoints; i++) {
  6783. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6784. }
  6785. return new Curve3(hermite);
  6786. };
  6787. /**
  6788. * Returns a Curve3 object along a CatmullRom Spline curve :
  6789. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6790. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6791. */
  6792. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6793. var totalPoints = new Array();
  6794. totalPoints.push(points[0].clone());
  6795. Array.prototype.push.apply(totalPoints, points);
  6796. totalPoints.push(points[points.length - 1].clone());
  6797. var catmullRom = new Array();
  6798. var step = 1.0 / nbPoints;
  6799. var amount = 0.0;
  6800. for (var i = 0; i < totalPoints.length - 3; i++) {
  6801. amount = 0;
  6802. for (var c = 0; c < nbPoints; c++) {
  6803. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6804. amount += step;
  6805. }
  6806. }
  6807. i--;
  6808. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6809. return new Curve3(catmullRom);
  6810. };
  6811. /**
  6812. * Returns the Curve3 stored array of successive Vector3
  6813. */
  6814. Curve3.prototype.getPoints = function () {
  6815. return this._points;
  6816. };
  6817. /**
  6818. * Returns the computed length (float) of the curve.
  6819. */
  6820. Curve3.prototype.length = function () {
  6821. return this._length;
  6822. };
  6823. /**
  6824. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6825. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6826. * curveA and curveB keep unchanged.
  6827. */
  6828. Curve3.prototype.continue = function (curve) {
  6829. var lastPoint = this._points[this._points.length - 1];
  6830. var continuedPoints = this._points.slice();
  6831. var curvePoints = curve.getPoints();
  6832. for (var i = 1; i < curvePoints.length; i++) {
  6833. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6834. }
  6835. var continuedCurve = new Curve3(continuedPoints);
  6836. return continuedCurve;
  6837. };
  6838. Curve3.prototype._computeLength = function (path) {
  6839. var l = 0;
  6840. for (var i = 1; i < path.length; i++) {
  6841. l += (path[i].subtract(path[i - 1])).length();
  6842. }
  6843. return l;
  6844. };
  6845. return Curve3;
  6846. }());
  6847. BABYLON.Curve3 = Curve3;
  6848. // Vertex formats
  6849. var PositionNormalVertex = /** @class */ (function () {
  6850. function PositionNormalVertex(position, normal) {
  6851. if (position === void 0) { position = Vector3.Zero(); }
  6852. if (normal === void 0) { normal = Vector3.Up(); }
  6853. this.position = position;
  6854. this.normal = normal;
  6855. }
  6856. PositionNormalVertex.prototype.clone = function () {
  6857. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6858. };
  6859. return PositionNormalVertex;
  6860. }());
  6861. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6862. var PositionNormalTextureVertex = /** @class */ (function () {
  6863. function PositionNormalTextureVertex(position, normal, uv) {
  6864. if (position === void 0) { position = Vector3.Zero(); }
  6865. if (normal === void 0) { normal = Vector3.Up(); }
  6866. if (uv === void 0) { uv = Vector2.Zero(); }
  6867. this.position = position;
  6868. this.normal = normal;
  6869. this.uv = uv;
  6870. }
  6871. PositionNormalTextureVertex.prototype.clone = function () {
  6872. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6873. };
  6874. return PositionNormalTextureVertex;
  6875. }());
  6876. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6877. // Temporary pre-allocated objects for engine internal use
  6878. // usage in any internal function :
  6879. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6880. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6881. var Tmp = /** @class */ (function () {
  6882. function Tmp() {
  6883. }
  6884. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6885. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6886. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6887. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6888. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6889. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6890. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6891. Matrix.Zero(), Matrix.Zero(),
  6892. Matrix.Zero(), Matrix.Zero(),
  6893. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6894. return Tmp;
  6895. }());
  6896. BABYLON.Tmp = Tmp;
  6897. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6898. var MathTmp = /** @class */ (function () {
  6899. function MathTmp() {
  6900. }
  6901. MathTmp.Vector3 = [Vector3.Zero()];
  6902. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6903. MathTmp.Quaternion = [Quaternion.Zero()];
  6904. return MathTmp;
  6905. }());
  6906. })(BABYLON || (BABYLON = {}));
  6907. //# sourceMappingURL=babylon.math.js.map
  6908. "use strict";
  6909. var BABYLON;
  6910. (function (BABYLON) {
  6911. var Scalar = /** @class */ (function () {
  6912. function Scalar() {
  6913. }
  6914. /**
  6915. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6916. */
  6917. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6918. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6919. var num = a - b;
  6920. return -epsilon <= num && num <= epsilon;
  6921. };
  6922. /**
  6923. * Returns a string : the upper case translation of the number i to hexadecimal.
  6924. */
  6925. Scalar.ToHex = function (i) {
  6926. var str = i.toString(16);
  6927. if (i <= 15) {
  6928. return ("0" + str).toUpperCase();
  6929. }
  6930. return str.toUpperCase();
  6931. };
  6932. /**
  6933. * Returns -1 if value is negative and +1 is value is positive.
  6934. * Returns the value itself if it's equal to zero.
  6935. */
  6936. Scalar.Sign = function (value) {
  6937. value = +value; // convert to a number
  6938. if (value === 0 || isNaN(value))
  6939. return value;
  6940. return value > 0 ? 1 : -1;
  6941. };
  6942. /**
  6943. * Returns the value itself if it's between min and max.
  6944. * Returns min if the value is lower than min.
  6945. * Returns max if the value is greater than max.
  6946. */
  6947. Scalar.Clamp = function (value, min, max) {
  6948. if (min === void 0) { min = 0; }
  6949. if (max === void 0) { max = 1; }
  6950. return Math.min(max, Math.max(min, value));
  6951. };
  6952. /**
  6953. * Returns the log2 of value.
  6954. */
  6955. Scalar.Log2 = function (value) {
  6956. return Math.log(value) * Math.LOG2E;
  6957. };
  6958. /**
  6959. * Loops the value, so that it is never larger than length and never smaller than 0.
  6960. *
  6961. * This is similar to the modulo operator but it works with floating point numbers.
  6962. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6963. * With t = 5 and length = 2.5, the result would be 0.0.
  6964. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6965. */
  6966. Scalar.Repeat = function (value, length) {
  6967. return value - Math.floor(value / length) * length;
  6968. };
  6969. /**
  6970. * Normalize the value between 0.0 and 1.0 using min and max values
  6971. */
  6972. Scalar.Normalize = function (value, min, max) {
  6973. return (value - min) / (max - min);
  6974. };
  6975. /**
  6976. * Denormalize the value from 0.0 and 1.0 using min and max values
  6977. */
  6978. Scalar.Denormalize = function (normalized, min, max) {
  6979. return (normalized * (max - min) + min);
  6980. };
  6981. /**
  6982. * Calculates the shortest difference between two given angles given in degrees.
  6983. */
  6984. Scalar.DeltaAngle = function (current, target) {
  6985. var num = Scalar.Repeat(target - current, 360.0);
  6986. if (num > 180.0) {
  6987. num -= 360.0;
  6988. }
  6989. return num;
  6990. };
  6991. /**
  6992. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6993. *
  6994. * The returned value will move back and forth between 0 and length
  6995. */
  6996. Scalar.PingPong = function (tx, length) {
  6997. var t = Scalar.Repeat(tx, length * 2.0);
  6998. return length - Math.abs(t - length);
  6999. };
  7000. /**
  7001. * Interpolates between min and max with smoothing at the limits.
  7002. *
  7003. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7004. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7005. */
  7006. Scalar.SmoothStep = function (from, to, tx) {
  7007. var t = Scalar.Clamp(tx);
  7008. t = -2.0 * t * t * t + 3.0 * t * t;
  7009. return to * t + from * (1.0 - t);
  7010. };
  7011. /**
  7012. * Moves a value current towards target.
  7013. *
  7014. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7015. * Negative values of maxDelta pushes the value away from target.
  7016. */
  7017. Scalar.MoveTowards = function (current, target, maxDelta) {
  7018. var result = 0;
  7019. if (Math.abs(target - current) <= maxDelta) {
  7020. result = target;
  7021. }
  7022. else {
  7023. result = current + Scalar.Sign(target - current) * maxDelta;
  7024. }
  7025. return result;
  7026. };
  7027. /**
  7028. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7029. *
  7030. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7031. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7032. */
  7033. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7034. var num = Scalar.DeltaAngle(current, target);
  7035. var result = 0;
  7036. if (-maxDelta < num && num < maxDelta) {
  7037. result = target;
  7038. }
  7039. else {
  7040. target = current + num;
  7041. result = Scalar.MoveTowards(current, target, maxDelta);
  7042. }
  7043. return result;
  7044. };
  7045. /**
  7046. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7047. */
  7048. Scalar.Lerp = function (start, end, amount) {
  7049. return start + ((end - start) * amount);
  7050. };
  7051. /**
  7052. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7053. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7054. */
  7055. Scalar.LerpAngle = function (start, end, amount) {
  7056. var num = Scalar.Repeat(end - start, 360.0);
  7057. if (num > 180.0) {
  7058. num -= 360.0;
  7059. }
  7060. return start + num * Scalar.Clamp(amount);
  7061. };
  7062. /**
  7063. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7064. */
  7065. Scalar.InverseLerp = function (a, b, value) {
  7066. var result = 0;
  7067. if (a != b) {
  7068. result = Scalar.Clamp((value - a) / (b - a));
  7069. }
  7070. else {
  7071. result = 0.0;
  7072. }
  7073. return result;
  7074. };
  7075. /**
  7076. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7077. */
  7078. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7079. var squared = amount * amount;
  7080. var cubed = amount * squared;
  7081. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7082. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7083. var part3 = (cubed - (2.0 * squared)) + amount;
  7084. var part4 = cubed - squared;
  7085. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7086. };
  7087. /**
  7088. * Returns a random float number between and min and max values
  7089. */
  7090. Scalar.RandomRange = function (min, max) {
  7091. if (min === max)
  7092. return min;
  7093. return ((Math.random() * (max - min)) + min);
  7094. };
  7095. /**
  7096. * This function returns percentage of a number in a given range.
  7097. *
  7098. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7099. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7100. */
  7101. Scalar.RangeToPercent = function (number, min, max) {
  7102. return ((number - min) / (max - min));
  7103. };
  7104. /**
  7105. * This function returns number that corresponds to the percentage in a given range.
  7106. *
  7107. * PercentToRange(0.34,0,100) will return 34.
  7108. */
  7109. Scalar.PercentToRange = function (percent, min, max) {
  7110. return ((max - min) * percent + min);
  7111. };
  7112. /**
  7113. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7114. * @param angle The angle to normalize in radian.
  7115. * @return The converted angle.
  7116. */
  7117. Scalar.NormalizeRadians = function (angle) {
  7118. // More precise but slower version kept for reference.
  7119. // angle = angle % Tools.TwoPi;
  7120. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7121. //if (angle > Math.PI) {
  7122. // angle -= Tools.TwoPi;
  7123. //}
  7124. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7125. return angle;
  7126. };
  7127. /**
  7128. * Two pi constants convenient for computation.
  7129. */
  7130. Scalar.TwoPi = Math.PI * 2;
  7131. return Scalar;
  7132. }());
  7133. BABYLON.Scalar = Scalar;
  7134. })(BABYLON || (BABYLON = {}));
  7135. //# sourceMappingURL=babylon.math.scalar.js.map
  7136. "use strict";
  7137. //# sourceMappingURL=babylon.mixins.js.map
  7138. "use strict";
  7139. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7140. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7141. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7142. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7143. //# sourceMappingURL=babylon.webgl2.js.map
  7144. "use strict";
  7145. var BABYLON;
  7146. (function (BABYLON) {
  7147. var __decoratorInitialStore = {};
  7148. var __mergedStore = {};
  7149. var _copySource = function (creationFunction, source, instanciate) {
  7150. var destination = creationFunction();
  7151. // Tags
  7152. if (BABYLON.Tags) {
  7153. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7154. }
  7155. var classStore = getMergedStore(destination);
  7156. // Properties
  7157. for (var property in classStore) {
  7158. var propertyDescriptor = classStore[property];
  7159. var sourceProperty = source[property];
  7160. var propertyType = propertyDescriptor.type;
  7161. if (sourceProperty !== undefined && sourceProperty !== null) {
  7162. switch (propertyType) {
  7163. case 0: // Value
  7164. case 6:// Mesh reference
  7165. destination[property] = sourceProperty;
  7166. break;
  7167. case 1:// Texture
  7168. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7169. break;
  7170. case 2: // Color3
  7171. case 3: // FresnelParameters
  7172. case 4: // Vector2
  7173. case 5: // Vector3
  7174. case 7: // Color Curves
  7175. case 10:// Quaternion
  7176. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7177. break;
  7178. }
  7179. }
  7180. }
  7181. return destination;
  7182. };
  7183. function getDirectStore(target) {
  7184. var classKey = target.getClassName();
  7185. if (!__decoratorInitialStore[classKey]) {
  7186. __decoratorInitialStore[classKey] = {};
  7187. }
  7188. return __decoratorInitialStore[classKey];
  7189. }
  7190. /**
  7191. * Return the list of properties flagged as serializable
  7192. * @param target: host object
  7193. */
  7194. function getMergedStore(target) {
  7195. var classKey = target.getClassName();
  7196. if (__mergedStore[classKey]) {
  7197. return __mergedStore[classKey];
  7198. }
  7199. __mergedStore[classKey] = {};
  7200. var store = __mergedStore[classKey];
  7201. var currentTarget = target;
  7202. var currentKey = classKey;
  7203. while (currentKey) {
  7204. var initialStore = __decoratorInitialStore[currentKey];
  7205. for (var property in initialStore) {
  7206. store[property] = initialStore[property];
  7207. }
  7208. var parent_1 = void 0;
  7209. var done = false;
  7210. do {
  7211. parent_1 = Object.getPrototypeOf(currentTarget);
  7212. if (!parent_1.getClassName) {
  7213. done = true;
  7214. break;
  7215. }
  7216. if (parent_1.getClassName() !== currentKey) {
  7217. break;
  7218. }
  7219. currentTarget = parent_1;
  7220. } while (parent_1);
  7221. if (done) {
  7222. break;
  7223. }
  7224. currentKey = parent_1.getClassName();
  7225. currentTarget = parent_1;
  7226. }
  7227. return store;
  7228. }
  7229. function generateSerializableMember(type, sourceName) {
  7230. return function (target, propertyKey) {
  7231. var classStore = getDirectStore(target);
  7232. if (!classStore[propertyKey]) {
  7233. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7234. }
  7235. };
  7236. }
  7237. function generateExpandMember(setCallback, targetKey) {
  7238. if (targetKey === void 0) { targetKey = null; }
  7239. return function (target, propertyKey) {
  7240. var key = targetKey || ("_" + propertyKey);
  7241. Object.defineProperty(target, propertyKey, {
  7242. get: function () {
  7243. return this[key];
  7244. },
  7245. set: function (value) {
  7246. if (this[key] === value) {
  7247. return;
  7248. }
  7249. this[key] = value;
  7250. target[setCallback].apply(this);
  7251. },
  7252. enumerable: true,
  7253. configurable: true
  7254. });
  7255. };
  7256. }
  7257. function expandToProperty(callback, targetKey) {
  7258. if (targetKey === void 0) { targetKey = null; }
  7259. return generateExpandMember(callback, targetKey);
  7260. }
  7261. BABYLON.expandToProperty = expandToProperty;
  7262. function serialize(sourceName) {
  7263. return generateSerializableMember(0, sourceName); // value member
  7264. }
  7265. BABYLON.serialize = serialize;
  7266. function serializeAsTexture(sourceName) {
  7267. return generateSerializableMember(1, sourceName); // texture member
  7268. }
  7269. BABYLON.serializeAsTexture = serializeAsTexture;
  7270. function serializeAsColor3(sourceName) {
  7271. return generateSerializableMember(2, sourceName); // color3 member
  7272. }
  7273. BABYLON.serializeAsColor3 = serializeAsColor3;
  7274. function serializeAsFresnelParameters(sourceName) {
  7275. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7276. }
  7277. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7278. function serializeAsVector2(sourceName) {
  7279. return generateSerializableMember(4, sourceName); // vector2 member
  7280. }
  7281. BABYLON.serializeAsVector2 = serializeAsVector2;
  7282. function serializeAsVector3(sourceName) {
  7283. return generateSerializableMember(5, sourceName); // vector3 member
  7284. }
  7285. BABYLON.serializeAsVector3 = serializeAsVector3;
  7286. function serializeAsMeshReference(sourceName) {
  7287. return generateSerializableMember(6, sourceName); // mesh reference member
  7288. }
  7289. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7290. function serializeAsColorCurves(sourceName) {
  7291. return generateSerializableMember(7, sourceName); // color curves
  7292. }
  7293. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7294. function serializeAsColor4(sourceName) {
  7295. return generateSerializableMember(8, sourceName); // color 4
  7296. }
  7297. BABYLON.serializeAsColor4 = serializeAsColor4;
  7298. function serializeAsImageProcessingConfiguration(sourceName) {
  7299. return generateSerializableMember(9, sourceName); // image processing
  7300. }
  7301. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7302. function serializeAsQuaternion(sourceName) {
  7303. return generateSerializableMember(10, sourceName); // quaternion member
  7304. }
  7305. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7306. var SerializationHelper = /** @class */ (function () {
  7307. function SerializationHelper() {
  7308. }
  7309. SerializationHelper.Serialize = function (entity, serializationObject) {
  7310. if (!serializationObject) {
  7311. serializationObject = {};
  7312. }
  7313. // Tags
  7314. if (BABYLON.Tags) {
  7315. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7316. }
  7317. var serializedProperties = getMergedStore(entity);
  7318. // Properties
  7319. for (var property in serializedProperties) {
  7320. var propertyDescriptor = serializedProperties[property];
  7321. var targetPropertyName = propertyDescriptor.sourceName || property;
  7322. var propertyType = propertyDescriptor.type;
  7323. var sourceProperty = entity[property];
  7324. if (sourceProperty !== undefined && sourceProperty !== null) {
  7325. switch (propertyType) {
  7326. case 0:// Value
  7327. serializationObject[targetPropertyName] = sourceProperty;
  7328. break;
  7329. case 1:// Texture
  7330. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7331. break;
  7332. case 2:// Color3
  7333. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7334. break;
  7335. case 3:// FresnelParameters
  7336. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7337. break;
  7338. case 4:// Vector2
  7339. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7340. break;
  7341. case 5:// Vector3
  7342. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7343. break;
  7344. case 6:// Mesh reference
  7345. serializationObject[targetPropertyName] = sourceProperty.id;
  7346. break;
  7347. case 7:// Color Curves
  7348. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7349. break;
  7350. case 8:// Color 4
  7351. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7352. break;
  7353. case 9:// Image Processing
  7354. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7355. break;
  7356. }
  7357. }
  7358. }
  7359. return serializationObject;
  7360. };
  7361. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7362. if (rootUrl === void 0) { rootUrl = null; }
  7363. var destination = creationFunction();
  7364. if (!rootUrl) {
  7365. rootUrl = "";
  7366. }
  7367. // Tags
  7368. if (BABYLON.Tags) {
  7369. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7370. }
  7371. var classStore = getMergedStore(destination);
  7372. // Properties
  7373. for (var property in classStore) {
  7374. var propertyDescriptor = classStore[property];
  7375. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7376. var propertyType = propertyDescriptor.type;
  7377. if (sourceProperty !== undefined && sourceProperty !== null) {
  7378. var dest = destination;
  7379. switch (propertyType) {
  7380. case 0:// Value
  7381. dest[property] = sourceProperty;
  7382. break;
  7383. case 1:// Texture
  7384. if (scene) {
  7385. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7386. }
  7387. break;
  7388. case 2:// Color3
  7389. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7390. break;
  7391. case 3:// FresnelParameters
  7392. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7393. break;
  7394. case 4:// Vector2
  7395. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7396. break;
  7397. case 5:// Vector3
  7398. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7399. break;
  7400. case 6:// Mesh reference
  7401. if (scene) {
  7402. dest[property] = scene.getLastMeshByID(sourceProperty);
  7403. }
  7404. break;
  7405. case 7:// Color Curves
  7406. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7407. break;
  7408. case 8:// Color 4
  7409. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7410. break;
  7411. case 9:// Image Processing
  7412. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7413. break;
  7414. }
  7415. }
  7416. }
  7417. return destination;
  7418. };
  7419. SerializationHelper.Clone = function (creationFunction, source) {
  7420. return _copySource(creationFunction, source, false);
  7421. };
  7422. SerializationHelper.Instanciate = function (creationFunction, source) {
  7423. return _copySource(creationFunction, source, true);
  7424. };
  7425. return SerializationHelper;
  7426. }());
  7427. BABYLON.SerializationHelper = SerializationHelper;
  7428. })(BABYLON || (BABYLON = {}));
  7429. //# sourceMappingURL=babylon.decorators.js.map
  7430. "use strict";
  7431. var BABYLON;
  7432. (function (BABYLON) {
  7433. /**
  7434. * Wrapper class for promise with external resolve and reject.
  7435. */
  7436. var Deferred = /** @class */ (function () {
  7437. /**
  7438. * Constructor for this deferred object.
  7439. */
  7440. function Deferred() {
  7441. var _this = this;
  7442. this.promise = new Promise(function (resolve, reject) {
  7443. _this._resolve = resolve;
  7444. _this._reject = reject;
  7445. });
  7446. }
  7447. Object.defineProperty(Deferred.prototype, "resolve", {
  7448. /**
  7449. * The resolve method of the promise associated with this deferred object.
  7450. */
  7451. get: function () {
  7452. return this._resolve;
  7453. },
  7454. enumerable: true,
  7455. configurable: true
  7456. });
  7457. Object.defineProperty(Deferred.prototype, "reject", {
  7458. /**
  7459. * The reject method of the promise associated with this deferred object.
  7460. */
  7461. get: function () {
  7462. return this._reject;
  7463. },
  7464. enumerable: true,
  7465. configurable: true
  7466. });
  7467. return Deferred;
  7468. }());
  7469. BABYLON.Deferred = Deferred;
  7470. })(BABYLON || (BABYLON = {}));
  7471. //# sourceMappingURL=babylon.deferred.js.map
  7472. "use strict";
  7473. var BABYLON;
  7474. (function (BABYLON) {
  7475. /**
  7476. * A class serves as a medium between the observable and its observers
  7477. */
  7478. var EventState = /** @class */ (function () {
  7479. /**
  7480. * Create a new EventState
  7481. * @param mask defines the mask associated with this state
  7482. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7483. * @param target defines the original target of the state
  7484. * @param currentTarget defines the current target of the state
  7485. */
  7486. function EventState(mask, skipNextObservers, target, currentTarget) {
  7487. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7488. this.initalize(mask, skipNextObservers, target, currentTarget);
  7489. }
  7490. /**
  7491. * Initialize the current event state
  7492. * @param mask defines the mask associated with this state
  7493. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7494. * @param target defines the original target of the state
  7495. * @param currentTarget defines the current target of the state
  7496. * @returns the current event state
  7497. */
  7498. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7499. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7500. this.mask = mask;
  7501. this.skipNextObservers = skipNextObservers;
  7502. this.target = target;
  7503. this.currentTarget = currentTarget;
  7504. return this;
  7505. };
  7506. return EventState;
  7507. }());
  7508. BABYLON.EventState = EventState;
  7509. /**
  7510. * Represent an Observer registered to a given Observable object.
  7511. */
  7512. var Observer = /** @class */ (function () {
  7513. /**
  7514. * Creates a new observer
  7515. * @param callback defines the callback to call when the observer is notified
  7516. * @param mask defines the mask of the observer (used to filter notifications)
  7517. * @param scope defines the current scope used to restore the JS context
  7518. */
  7519. function Observer(
  7520. /**
  7521. * Defines the callback to call when the observer is notified
  7522. */
  7523. callback,
  7524. /**
  7525. * Defines the mask of the observer (used to filter notifications)
  7526. */
  7527. mask,
  7528. /**
  7529. * Defines the current scope used to restore the JS context
  7530. */
  7531. scope) {
  7532. if (scope === void 0) { scope = null; }
  7533. this.callback = callback;
  7534. this.mask = mask;
  7535. this.scope = scope;
  7536. /** @ignore */
  7537. this._willBeUnregistered = false;
  7538. /**
  7539. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7540. */
  7541. this.unregisterOnNextCall = false;
  7542. }
  7543. return Observer;
  7544. }());
  7545. BABYLON.Observer = Observer;
  7546. /**
  7547. * Represent a list of observers registered to multiple Observables object.
  7548. */
  7549. var MultiObserver = /** @class */ (function () {
  7550. function MultiObserver() {
  7551. }
  7552. /**
  7553. * Release associated resources
  7554. */
  7555. MultiObserver.prototype.dispose = function () {
  7556. if (this._observers && this._observables) {
  7557. for (var index = 0; index < this._observers.length; index++) {
  7558. this._observables[index].remove(this._observers[index]);
  7559. }
  7560. }
  7561. this._observers = null;
  7562. this._observables = null;
  7563. };
  7564. /**
  7565. * Raise a callback when one of the observable will notify
  7566. * @param observables defines a list of observables to watch
  7567. * @param callback defines the callback to call on notification
  7568. * @param mask defines the mask used to filter notifications
  7569. * @param scope defines the current scope used to restore the JS context
  7570. * @returns the new MultiObserver
  7571. */
  7572. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7573. if (mask === void 0) { mask = -1; }
  7574. if (scope === void 0) { scope = null; }
  7575. var result = new MultiObserver();
  7576. result._observers = new Array();
  7577. result._observables = observables;
  7578. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7579. var observable = observables_1[_i];
  7580. var observer = observable.add(callback, mask, false, scope);
  7581. if (observer) {
  7582. result._observers.push(observer);
  7583. }
  7584. }
  7585. return result;
  7586. };
  7587. return MultiObserver;
  7588. }());
  7589. BABYLON.MultiObserver = MultiObserver;
  7590. /**
  7591. * The Observable class is a simple implementation of the Observable pattern.
  7592. * 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.
  7593. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7594. * 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).
  7595. * 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.
  7596. */
  7597. var Observable = /** @class */ (function () {
  7598. /**
  7599. * Creates a new observable
  7600. * @param onObserverAdded defines a callback to call when a new observer is added
  7601. */
  7602. function Observable(onObserverAdded) {
  7603. this._observers = new Array();
  7604. this._eventState = new EventState(0);
  7605. if (onObserverAdded) {
  7606. this._onObserverAdded = onObserverAdded;
  7607. }
  7608. }
  7609. /**
  7610. * Create a new Observer with the specified callback
  7611. * @param callback the callback that will be executed for that Observer
  7612. * @param mask the mask used to filter observers
  7613. * @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.
  7614. * @param scope optional scope for the callback to be called from
  7615. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7616. * @returns the new observer created for the callback
  7617. */
  7618. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7619. if (mask === void 0) { mask = -1; }
  7620. if (insertFirst === void 0) { insertFirst = false; }
  7621. if (scope === void 0) { scope = null; }
  7622. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7623. if (!callback) {
  7624. return null;
  7625. }
  7626. var observer = new Observer(callback, mask, scope);
  7627. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7628. if (insertFirst) {
  7629. this._observers.unshift(observer);
  7630. }
  7631. else {
  7632. this._observers.push(observer);
  7633. }
  7634. if (this._onObserverAdded) {
  7635. this._onObserverAdded(observer);
  7636. }
  7637. return observer;
  7638. };
  7639. /**
  7640. * Remove an Observer from the Observable object
  7641. * @param observer the instance of the Observer to remove
  7642. * @returns false if it doesn't belong to this Observable
  7643. */
  7644. Observable.prototype.remove = function (observer) {
  7645. if (!observer) {
  7646. return false;
  7647. }
  7648. var index = this._observers.indexOf(observer);
  7649. if (index !== -1) {
  7650. this._observers.splice(index, 1);
  7651. return true;
  7652. }
  7653. return false;
  7654. };
  7655. /**
  7656. * Remove a callback from the Observable object
  7657. * @param callback the callback to remove
  7658. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7659. * @returns false if it doesn't belong to this Observable
  7660. */
  7661. Observable.prototype.removeCallback = function (callback, scope) {
  7662. for (var index = 0; index < this._observers.length; index++) {
  7663. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7664. this._observers.splice(index, 1);
  7665. return true;
  7666. }
  7667. }
  7668. return false;
  7669. };
  7670. Observable.prototype._deferUnregister = function (observer) {
  7671. var _this = this;
  7672. observer.unregisterOnNextCall = false;
  7673. observer._willBeUnregistered = true;
  7674. BABYLON.Tools.SetImmediate(function () {
  7675. _this.remove(observer);
  7676. });
  7677. };
  7678. /**
  7679. * Notify all Observers by calling their respective callback with the given data
  7680. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7681. * @param eventData defines the data to send to all observers
  7682. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7683. * @param target defines the original target of the state
  7684. * @param currentTarget defines the current target of the state
  7685. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7686. */
  7687. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7688. if (mask === void 0) { mask = -1; }
  7689. if (!this._observers.length) {
  7690. return true;
  7691. }
  7692. var state = this._eventState;
  7693. state.mask = mask;
  7694. state.target = target;
  7695. state.currentTarget = currentTarget;
  7696. state.skipNextObservers = false;
  7697. state.lastReturnValue = eventData;
  7698. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7699. var obs = _a[_i];
  7700. if (obs._willBeUnregistered) {
  7701. continue;
  7702. }
  7703. if (obs.mask & mask) {
  7704. if (obs.scope) {
  7705. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7706. }
  7707. else {
  7708. state.lastReturnValue = obs.callback(eventData, state);
  7709. }
  7710. if (obs.unregisterOnNextCall) {
  7711. this._deferUnregister(obs);
  7712. }
  7713. }
  7714. if (state.skipNextObservers) {
  7715. return false;
  7716. }
  7717. }
  7718. return true;
  7719. };
  7720. /**
  7721. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7722. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7723. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7724. * and it is crucial that all callbacks will be executed.
  7725. * The order of the callbacks is kept, callbacks are not executed parallel.
  7726. *
  7727. * @param eventData The data to be sent to each callback
  7728. * @param mask is used to filter observers defaults to -1
  7729. * @param target defines the callback target (see EventState)
  7730. * @param currentTarget defines he current object in the bubbling phase
  7731. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7732. */
  7733. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7734. var _this = this;
  7735. if (mask === void 0) { mask = -1; }
  7736. // create an empty promise
  7737. var p = Promise.resolve(eventData);
  7738. // no observers? return this promise.
  7739. if (!this._observers.length) {
  7740. return p;
  7741. }
  7742. var state = this._eventState;
  7743. state.mask = mask;
  7744. state.target = target;
  7745. state.currentTarget = currentTarget;
  7746. state.skipNextObservers = false;
  7747. // execute one callback after another (not using Promise.all, the order is important)
  7748. this._observers.forEach(function (obs) {
  7749. if (state.skipNextObservers) {
  7750. return;
  7751. }
  7752. if (obs._willBeUnregistered) {
  7753. return;
  7754. }
  7755. if (obs.mask & mask) {
  7756. if (obs.scope) {
  7757. p = p.then(function (lastReturnedValue) {
  7758. state.lastReturnValue = lastReturnedValue;
  7759. return obs.callback.apply(obs.scope, [eventData, state]);
  7760. });
  7761. }
  7762. else {
  7763. p = p.then(function (lastReturnedValue) {
  7764. state.lastReturnValue = lastReturnedValue;
  7765. return obs.callback(eventData, state);
  7766. });
  7767. }
  7768. if (obs.unregisterOnNextCall) {
  7769. _this._deferUnregister(obs);
  7770. }
  7771. }
  7772. });
  7773. // return the eventData
  7774. return p.then(function () { return eventData; });
  7775. };
  7776. /**
  7777. * Notify a specific observer
  7778. * @param observer defines the observer to notify
  7779. * @param eventData defines the data to be sent to each callback
  7780. * @param mask is used to filter observers defaults to -1
  7781. */
  7782. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7783. if (mask === void 0) { mask = -1; }
  7784. var state = this._eventState;
  7785. state.mask = mask;
  7786. state.skipNextObservers = false;
  7787. observer.callback(eventData, state);
  7788. };
  7789. /**
  7790. * Gets a boolean indicating if the observable has at least one observer
  7791. * @returns true is the Observable has at least one Observer registered
  7792. */
  7793. Observable.prototype.hasObservers = function () {
  7794. return this._observers.length > 0;
  7795. };
  7796. /**
  7797. * Clear the list of observers
  7798. */
  7799. Observable.prototype.clear = function () {
  7800. this._observers = new Array();
  7801. this._onObserverAdded = null;
  7802. };
  7803. /**
  7804. * Clone the current observable
  7805. * @returns a new observable
  7806. */
  7807. Observable.prototype.clone = function () {
  7808. var result = new Observable();
  7809. result._observers = this._observers.slice(0);
  7810. return result;
  7811. };
  7812. /**
  7813. * Does this observable handles observer registered with a given mask
  7814. * @param mask defines the mask to be tested
  7815. * @return whether or not one observer registered with the given mask is handeled
  7816. **/
  7817. Observable.prototype.hasSpecificMask = function (mask) {
  7818. if (mask === void 0) { mask = -1; }
  7819. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7820. var obs = _a[_i];
  7821. if (obs.mask & mask || obs.mask === mask) {
  7822. return true;
  7823. }
  7824. }
  7825. return false;
  7826. };
  7827. return Observable;
  7828. }());
  7829. BABYLON.Observable = Observable;
  7830. })(BABYLON || (BABYLON = {}));
  7831. //# sourceMappingURL=babylon.observable.js.map
  7832. "use strict";
  7833. var BABYLON;
  7834. (function (BABYLON) {
  7835. var SmartArray = /** @class */ (function () {
  7836. function SmartArray(capacity) {
  7837. this.length = 0;
  7838. this.data = new Array(capacity);
  7839. this._id = SmartArray._GlobalId++;
  7840. }
  7841. SmartArray.prototype.push = function (value) {
  7842. this.data[this.length++] = value;
  7843. if (this.length > this.data.length) {
  7844. this.data.length *= 2;
  7845. }
  7846. };
  7847. SmartArray.prototype.forEach = function (func) {
  7848. for (var index = 0; index < this.length; index++) {
  7849. func(this.data[index]);
  7850. }
  7851. };
  7852. SmartArray.prototype.sort = function (compareFn) {
  7853. this.data.sort(compareFn);
  7854. };
  7855. SmartArray.prototype.reset = function () {
  7856. this.length = 0;
  7857. };
  7858. SmartArray.prototype.dispose = function () {
  7859. this.reset();
  7860. if (this.data) {
  7861. this.data.length = 0;
  7862. this.data = [];
  7863. }
  7864. };
  7865. SmartArray.prototype.concat = function (array) {
  7866. if (array.length === 0) {
  7867. return;
  7868. }
  7869. if (this.length + array.length > this.data.length) {
  7870. this.data.length = (this.length + array.length) * 2;
  7871. }
  7872. for (var index = 0; index < array.length; index++) {
  7873. this.data[this.length++] = (array.data || array)[index];
  7874. }
  7875. };
  7876. SmartArray.prototype.indexOf = function (value) {
  7877. var position = this.data.indexOf(value);
  7878. if (position >= this.length) {
  7879. return -1;
  7880. }
  7881. return position;
  7882. };
  7883. SmartArray.prototype.contains = function (value) {
  7884. return this.data.indexOf(value) !== -1;
  7885. };
  7886. // Statics
  7887. SmartArray._GlobalId = 0;
  7888. return SmartArray;
  7889. }());
  7890. BABYLON.SmartArray = SmartArray;
  7891. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7892. __extends(SmartArrayNoDuplicate, _super);
  7893. function SmartArrayNoDuplicate() {
  7894. var _this = _super !== null && _super.apply(this, arguments) || this;
  7895. _this._duplicateId = 0;
  7896. return _this;
  7897. }
  7898. SmartArrayNoDuplicate.prototype.push = function (value) {
  7899. _super.prototype.push.call(this, value);
  7900. if (!value.__smartArrayFlags) {
  7901. value.__smartArrayFlags = {};
  7902. }
  7903. value.__smartArrayFlags[this._id] = this._duplicateId;
  7904. };
  7905. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7906. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7907. return false;
  7908. }
  7909. this.push(value);
  7910. return true;
  7911. };
  7912. SmartArrayNoDuplicate.prototype.reset = function () {
  7913. _super.prototype.reset.call(this);
  7914. this._duplicateId++;
  7915. };
  7916. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7917. if (array.length === 0) {
  7918. return;
  7919. }
  7920. if (this.length + array.length > this.data.length) {
  7921. this.data.length = (this.length + array.length) * 2;
  7922. }
  7923. for (var index = 0; index < array.length; index++) {
  7924. var item = (array.data || array)[index];
  7925. this.pushNoDuplicate(item);
  7926. }
  7927. };
  7928. return SmartArrayNoDuplicate;
  7929. }(SmartArray));
  7930. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7931. })(BABYLON || (BABYLON = {}));
  7932. //# sourceMappingURL=babylon.smartArray.js.map
  7933. "use strict";
  7934. var BABYLON;
  7935. (function (BABYLON) {
  7936. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7937. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7938. var LoadFileError = /** @class */ (function (_super) {
  7939. __extends(LoadFileError, _super);
  7940. function LoadFileError(message, request) {
  7941. var _this = _super.call(this, message) || this;
  7942. _this.request = request;
  7943. _this.name = "LoadFileError";
  7944. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7945. return _this;
  7946. }
  7947. // Polyfill for Object.setPrototypeOf if necessary.
  7948. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7949. return LoadFileError;
  7950. }(Error));
  7951. BABYLON.LoadFileError = LoadFileError;
  7952. var RetryStrategy = /** @class */ (function () {
  7953. function RetryStrategy() {
  7954. }
  7955. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7956. if (maxRetries === void 0) { maxRetries = 3; }
  7957. if (baseInterval === void 0) { baseInterval = 500; }
  7958. return function (url, request, retryIndex) {
  7959. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7960. return -1;
  7961. }
  7962. return Math.pow(2, retryIndex) * baseInterval;
  7963. };
  7964. };
  7965. return RetryStrategy;
  7966. }());
  7967. BABYLON.RetryStrategy = RetryStrategy;
  7968. // Screenshots
  7969. var screenshotCanvas;
  7970. var cloneValue = function (source, destinationObject) {
  7971. if (!source)
  7972. return null;
  7973. if (source instanceof BABYLON.Mesh) {
  7974. return null;
  7975. }
  7976. if (source instanceof BABYLON.SubMesh) {
  7977. return source.clone(destinationObject);
  7978. }
  7979. else if (source.clone) {
  7980. return source.clone();
  7981. }
  7982. return null;
  7983. };
  7984. var Tools = /** @class */ (function () {
  7985. function Tools() {
  7986. }
  7987. /**
  7988. * Interpolates between a and b via alpha
  7989. * @param a The lower value (returned when alpha = 0)
  7990. * @param b The upper value (returned when alpha = 1)
  7991. * @param alpha The interpolation-factor
  7992. * @return The mixed value
  7993. */
  7994. Tools.Mix = function (a, b, alpha) {
  7995. return a * (1 - alpha) + b * alpha;
  7996. };
  7997. Tools.Instantiate = function (className) {
  7998. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7999. return Tools.RegisteredExternalClasses[className];
  8000. }
  8001. var arr = className.split(".");
  8002. var fn = (window || this);
  8003. for (var i = 0, len = arr.length; i < len; i++) {
  8004. fn = fn[arr[i]];
  8005. }
  8006. if (typeof fn !== "function") {
  8007. return null;
  8008. }
  8009. return fn;
  8010. };
  8011. /**
  8012. * Provides a slice function that will work even on IE
  8013. * @param data defines the array to slice
  8014. * @returns the new sliced array
  8015. */
  8016. Tools.Slice = function (data) {
  8017. if (data.slice) {
  8018. return data.slice();
  8019. }
  8020. return Array.prototype.slice.call(data);
  8021. };
  8022. Tools.SetImmediate = function (action) {
  8023. if (window.setImmediate) {
  8024. window.setImmediate(action);
  8025. }
  8026. else {
  8027. setTimeout(action, 1);
  8028. }
  8029. };
  8030. Tools.IsExponentOfTwo = function (value) {
  8031. var count = 1;
  8032. do {
  8033. count *= 2;
  8034. } while (count < value);
  8035. return count === value;
  8036. };
  8037. /**
  8038. * Find the next highest power of two.
  8039. * @param x Number to start search from.
  8040. * @return Next highest power of two.
  8041. */
  8042. Tools.CeilingPOT = function (x) {
  8043. x--;
  8044. x |= x >> 1;
  8045. x |= x >> 2;
  8046. x |= x >> 4;
  8047. x |= x >> 8;
  8048. x |= x >> 16;
  8049. x++;
  8050. return x;
  8051. };
  8052. /**
  8053. * Find the next lowest power of two.
  8054. * @param x Number to start search from.
  8055. * @return Next lowest power of two.
  8056. */
  8057. Tools.FloorPOT = function (x) {
  8058. x = x | (x >> 1);
  8059. x = x | (x >> 2);
  8060. x = x | (x >> 4);
  8061. x = x | (x >> 8);
  8062. x = x | (x >> 16);
  8063. return x - (x >> 1);
  8064. };
  8065. /**
  8066. * Find the nearest power of two.
  8067. * @param x Number to start search from.
  8068. * @return Next nearest power of two.
  8069. */
  8070. Tools.NearestPOT = function (x) {
  8071. var c = Tools.CeilingPOT(x);
  8072. var f = Tools.FloorPOT(x);
  8073. return (c - x) > (x - f) ? f : c;
  8074. };
  8075. Tools.GetExponentOfTwo = function (value, max, mode) {
  8076. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8077. var pot;
  8078. switch (mode) {
  8079. case BABYLON.Engine.SCALEMODE_FLOOR:
  8080. pot = Tools.FloorPOT(value);
  8081. break;
  8082. case BABYLON.Engine.SCALEMODE_NEAREST:
  8083. pot = Tools.NearestPOT(value);
  8084. break;
  8085. case BABYLON.Engine.SCALEMODE_CEILING:
  8086. default:
  8087. pot = Tools.CeilingPOT(value);
  8088. break;
  8089. }
  8090. return Math.min(pot, max);
  8091. };
  8092. Tools.GetFilename = function (path) {
  8093. var index = path.lastIndexOf("/");
  8094. if (index < 0)
  8095. return path;
  8096. return path.substring(index + 1);
  8097. };
  8098. /**
  8099. * Extracts the "folder" part of a path (everything before the filename).
  8100. * @param uri The URI to extract the info from
  8101. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8102. * @returns The "folder" part of the path
  8103. */
  8104. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8105. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8106. var index = uri.lastIndexOf("/");
  8107. if (index < 0) {
  8108. if (returnUnchangedIfNoSlash) {
  8109. return uri;
  8110. }
  8111. return "";
  8112. }
  8113. return uri.substring(0, index + 1);
  8114. };
  8115. Tools.GetDOMTextContent = function (element) {
  8116. var result = "";
  8117. var child = element.firstChild;
  8118. while (child) {
  8119. if (child.nodeType === 3) {
  8120. result += child.textContent;
  8121. }
  8122. child = child.nextSibling;
  8123. }
  8124. return result;
  8125. };
  8126. Tools.ToDegrees = function (angle) {
  8127. return angle * 180 / Math.PI;
  8128. };
  8129. Tools.ToRadians = function (angle) {
  8130. return angle * Math.PI / 180;
  8131. };
  8132. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8133. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8134. var output = "";
  8135. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8136. var i = 0;
  8137. var bytes = new Uint8Array(buffer);
  8138. while (i < bytes.length) {
  8139. chr1 = bytes[i++];
  8140. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8141. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8142. enc1 = chr1 >> 2;
  8143. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8144. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8145. enc4 = chr3 & 63;
  8146. if (isNaN(chr2)) {
  8147. enc3 = enc4 = 64;
  8148. }
  8149. else if (isNaN(chr3)) {
  8150. enc4 = 64;
  8151. }
  8152. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8153. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8154. }
  8155. return "data:image/png;base64," + output;
  8156. };
  8157. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8158. if (bias === void 0) { bias = null; }
  8159. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8160. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8161. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8162. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8163. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8164. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8165. }
  8166. if (bias) {
  8167. minimum.x -= minimum.x * bias.x + bias.y;
  8168. minimum.y -= minimum.y * bias.x + bias.y;
  8169. minimum.z -= minimum.z * bias.x + bias.y;
  8170. maximum.x += maximum.x * bias.x + bias.y;
  8171. maximum.y += maximum.y * bias.x + bias.y;
  8172. maximum.z += maximum.z * bias.x + bias.y;
  8173. }
  8174. return {
  8175. minimum: minimum,
  8176. maximum: maximum
  8177. };
  8178. };
  8179. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8180. if (bias === void 0) { bias = null; }
  8181. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8182. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8183. if (!stride) {
  8184. stride = 3;
  8185. }
  8186. for (var index = start; index < start + count; index++) {
  8187. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8188. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8189. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8190. }
  8191. if (bias) {
  8192. minimum.x -= minimum.x * bias.x + bias.y;
  8193. minimum.y -= minimum.y * bias.x + bias.y;
  8194. minimum.z -= minimum.z * bias.x + bias.y;
  8195. maximum.x += maximum.x * bias.x + bias.y;
  8196. maximum.y += maximum.y * bias.x + bias.y;
  8197. maximum.z += maximum.z * bias.x + bias.y;
  8198. }
  8199. return {
  8200. minimum: minimum,
  8201. maximum: maximum
  8202. };
  8203. };
  8204. Tools.Vector2ArrayFeeder = function (array) {
  8205. return function (index) {
  8206. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8207. var length = isFloatArray ? array.length / 2 : array.length;
  8208. if (index >= length) {
  8209. return null;
  8210. }
  8211. if (isFloatArray) {
  8212. var fa = array;
  8213. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8214. }
  8215. var a = array;
  8216. return a[index];
  8217. };
  8218. };
  8219. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8220. if (bias === void 0) { bias = null; }
  8221. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8222. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8223. var i = 0;
  8224. var cur = feeder(i++);
  8225. while (cur) {
  8226. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8227. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8228. cur = feeder(i++);
  8229. }
  8230. if (bias) {
  8231. minimum.x -= minimum.x * bias.x + bias.y;
  8232. minimum.y -= minimum.y * bias.x + bias.y;
  8233. maximum.x += maximum.x * bias.x + bias.y;
  8234. maximum.y += maximum.y * bias.x + bias.y;
  8235. }
  8236. return {
  8237. minimum: minimum,
  8238. maximum: maximum
  8239. };
  8240. };
  8241. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8242. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8243. return null;
  8244. return Array.isArray(obj) ? obj : [obj];
  8245. };
  8246. // Misc.
  8247. Tools.GetPointerPrefix = function () {
  8248. var eventPrefix = "pointer";
  8249. // Check if pointer events are supported
  8250. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8251. eventPrefix = "mouse";
  8252. }
  8253. return eventPrefix;
  8254. };
  8255. /**
  8256. * @param func - the function to be called
  8257. * @param requester - the object that will request the next frame. Falls back to window.
  8258. */
  8259. Tools.QueueNewFrame = function (func, requester) {
  8260. if (!Tools.IsWindowObjectExist()) {
  8261. return setTimeout(func, 16);
  8262. }
  8263. if (!requester) {
  8264. requester = window;
  8265. }
  8266. if (requester.requestAnimationFrame) {
  8267. return requester.requestAnimationFrame(func);
  8268. }
  8269. else if (requester.msRequestAnimationFrame) {
  8270. return requester.msRequestAnimationFrame(func);
  8271. }
  8272. else if (requester.webkitRequestAnimationFrame) {
  8273. return requester.webkitRequestAnimationFrame(func);
  8274. }
  8275. else if (requester.mozRequestAnimationFrame) {
  8276. return requester.mozRequestAnimationFrame(func);
  8277. }
  8278. else if (requester.oRequestAnimationFrame) {
  8279. return requester.oRequestAnimationFrame(func);
  8280. }
  8281. else {
  8282. return window.setTimeout(func, 16);
  8283. }
  8284. };
  8285. Tools.RequestFullscreen = function (element) {
  8286. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8287. if (!requestFunction)
  8288. return;
  8289. requestFunction.call(element);
  8290. };
  8291. Tools.ExitFullscreen = function () {
  8292. if (document.exitFullscreen) {
  8293. document.exitFullscreen();
  8294. }
  8295. else if (document.mozCancelFullScreen) {
  8296. document.mozCancelFullScreen();
  8297. }
  8298. else if (document.webkitCancelFullScreen) {
  8299. document.webkitCancelFullScreen();
  8300. }
  8301. else if (document.msCancelFullScreen) {
  8302. document.msCancelFullScreen();
  8303. }
  8304. };
  8305. Tools.SetCorsBehavior = function (url, element) {
  8306. if (url && url.indexOf("data:") === 0) {
  8307. return;
  8308. }
  8309. if (Tools.CorsBehavior) {
  8310. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8311. element.crossOrigin = Tools.CorsBehavior;
  8312. }
  8313. else {
  8314. var result = Tools.CorsBehavior(url);
  8315. if (result) {
  8316. element.crossOrigin = result;
  8317. }
  8318. }
  8319. }
  8320. };
  8321. // External files
  8322. Tools.CleanUrl = function (url) {
  8323. url = url.replace(/#/mg, "%23");
  8324. return url;
  8325. };
  8326. Tools.LoadImage = function (url, onLoad, onError, database) {
  8327. if (url instanceof ArrayBuffer) {
  8328. url = Tools.EncodeArrayBufferTobase64(url);
  8329. }
  8330. url = Tools.CleanUrl(url);
  8331. url = Tools.PreprocessUrl(url);
  8332. var img = new Image();
  8333. Tools.SetCorsBehavior(url, img);
  8334. var loadHandler = function () {
  8335. img.removeEventListener("load", loadHandler);
  8336. img.removeEventListener("error", errorHandler);
  8337. onLoad(img);
  8338. };
  8339. var errorHandler = function (err) {
  8340. img.removeEventListener("load", loadHandler);
  8341. img.removeEventListener("error", errorHandler);
  8342. Tools.Error("Error while trying to load image: " + url);
  8343. if (onError) {
  8344. onError("Error while trying to load image: " + url, err);
  8345. }
  8346. };
  8347. img.addEventListener("load", loadHandler);
  8348. img.addEventListener("error", errorHandler);
  8349. var noIndexedDB = function () {
  8350. img.src = url;
  8351. };
  8352. var loadFromIndexedDB = function () {
  8353. if (database) {
  8354. database.loadImageFromDB(url, img);
  8355. }
  8356. };
  8357. //ANY database to do!
  8358. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8359. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8360. }
  8361. else {
  8362. if (url.indexOf("file:") !== -1) {
  8363. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8364. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8365. try {
  8366. var blobURL;
  8367. try {
  8368. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8369. }
  8370. catch (ex) {
  8371. // Chrome doesn't support oneTimeOnly parameter
  8372. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8373. }
  8374. img.src = blobURL;
  8375. }
  8376. catch (e) {
  8377. img.src = "";
  8378. }
  8379. return img;
  8380. }
  8381. }
  8382. noIndexedDB();
  8383. }
  8384. return img;
  8385. };
  8386. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8387. url = Tools.CleanUrl(url);
  8388. url = Tools.PreprocessUrl(url);
  8389. // If file and file input are set
  8390. if (url.indexOf("file:") !== -1) {
  8391. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8392. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8393. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8394. }
  8395. }
  8396. var loadUrl = Tools.BaseUrl + url;
  8397. var aborted = false;
  8398. var fileRequest = {
  8399. onCompleteObservable: new BABYLON.Observable(),
  8400. abort: function () { return aborted = true; },
  8401. };
  8402. var requestFile = function () {
  8403. var request = new XMLHttpRequest();
  8404. var retryHandle = null;
  8405. fileRequest.abort = function () {
  8406. aborted = true;
  8407. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8408. request.abort();
  8409. }
  8410. if (retryHandle !== null) {
  8411. clearTimeout(retryHandle);
  8412. retryHandle = null;
  8413. }
  8414. };
  8415. var retryLoop = function (retryIndex) {
  8416. request.open('GET', loadUrl, true);
  8417. if (useArrayBuffer) {
  8418. request.responseType = "arraybuffer";
  8419. }
  8420. if (onProgress) {
  8421. request.addEventListener("progress", onProgress);
  8422. }
  8423. var onLoadEnd = function () {
  8424. request.removeEventListener("loadend", onLoadEnd);
  8425. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8426. fileRequest.onCompleteObservable.clear();
  8427. };
  8428. request.addEventListener("loadend", onLoadEnd);
  8429. var onReadyStateChange = function () {
  8430. if (aborted) {
  8431. return;
  8432. }
  8433. // In case of undefined state in some browsers.
  8434. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8435. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8436. request.removeEventListener("readystatechange", onReadyStateChange);
  8437. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8438. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8439. return;
  8440. }
  8441. var retryStrategy = Tools.DefaultRetryStrategy;
  8442. if (retryStrategy) {
  8443. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8444. if (waitTime !== -1) {
  8445. // Prevent the request from completing for retry.
  8446. request.removeEventListener("loadend", onLoadEnd);
  8447. request = new XMLHttpRequest();
  8448. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8449. return;
  8450. }
  8451. }
  8452. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8453. if (onError) {
  8454. onError(request, e);
  8455. }
  8456. else {
  8457. throw e;
  8458. }
  8459. }
  8460. };
  8461. request.addEventListener("readystatechange", onReadyStateChange);
  8462. request.send();
  8463. };
  8464. retryLoop(0);
  8465. };
  8466. // Caching all files
  8467. if (database && database.enableSceneOffline) {
  8468. var noIndexedDB_1 = function () {
  8469. if (!aborted) {
  8470. requestFile();
  8471. }
  8472. };
  8473. var loadFromIndexedDB = function () {
  8474. // TODO: database needs to support aborting and should return a IFileRequest
  8475. if (aborted) {
  8476. return;
  8477. }
  8478. if (database) {
  8479. database.loadFileFromDB(url, function (data) {
  8480. if (!aborted) {
  8481. onSuccess(data);
  8482. }
  8483. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8484. }, onProgress ? function (event) {
  8485. if (!aborted) {
  8486. onProgress(event);
  8487. }
  8488. } : undefined, noIndexedDB_1, useArrayBuffer);
  8489. }
  8490. };
  8491. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8492. }
  8493. else {
  8494. requestFile();
  8495. }
  8496. return fileRequest;
  8497. };
  8498. /**
  8499. * Load a script (identified by an url). When the url returns, the
  8500. * content of this file is added into a new script element, attached to the DOM (body element)
  8501. */
  8502. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8503. var head = document.getElementsByTagName('head')[0];
  8504. var script = document.createElement('script');
  8505. script.type = 'text/javascript';
  8506. script.src = scriptUrl;
  8507. script.onload = function () {
  8508. if (onSuccess) {
  8509. onSuccess();
  8510. }
  8511. };
  8512. script.onerror = function (e) {
  8513. if (onError) {
  8514. onError("Unable to load script", e);
  8515. }
  8516. };
  8517. head.appendChild(script);
  8518. };
  8519. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8520. var reader = new FileReader();
  8521. var request = {
  8522. onCompleteObservable: new BABYLON.Observable(),
  8523. abort: function () { return reader.abort(); },
  8524. };
  8525. reader.onloadend = function (e) {
  8526. request.onCompleteObservable.notifyObservers(request);
  8527. };
  8528. reader.onload = function (e) {
  8529. //target doesn't have result from ts 1.3
  8530. callback(e.target['result']);
  8531. };
  8532. reader.onprogress = progressCallback;
  8533. reader.readAsDataURL(fileToLoad);
  8534. return request;
  8535. };
  8536. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8537. var reader = new FileReader();
  8538. var request = {
  8539. onCompleteObservable: new BABYLON.Observable(),
  8540. abort: function () { return reader.abort(); },
  8541. };
  8542. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8543. reader.onerror = function (e) {
  8544. Tools.Log("Error while reading file: " + fileToLoad.name);
  8545. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8546. };
  8547. reader.onload = function (e) {
  8548. //target doesn't have result from ts 1.3
  8549. callback(e.target['result']);
  8550. };
  8551. if (progressCallBack) {
  8552. reader.onprogress = progressCallBack;
  8553. }
  8554. if (!useArrayBuffer) {
  8555. // Asynchronous read
  8556. reader.readAsText(fileToLoad);
  8557. }
  8558. else {
  8559. reader.readAsArrayBuffer(fileToLoad);
  8560. }
  8561. return request;
  8562. };
  8563. //returns a downloadable url to a file content.
  8564. Tools.FileAsURL = function (content) {
  8565. var fileBlob = new Blob([content]);
  8566. var url = window.URL || window.webkitURL;
  8567. var link = url.createObjectURL(fileBlob);
  8568. return link;
  8569. };
  8570. // Misc.
  8571. Tools.Format = function (value, decimals) {
  8572. if (decimals === void 0) { decimals = 2; }
  8573. return value.toFixed(decimals);
  8574. };
  8575. Tools.CheckExtends = function (v, min, max) {
  8576. if (v.x < min.x)
  8577. min.x = v.x;
  8578. if (v.y < min.y)
  8579. min.y = v.y;
  8580. if (v.z < min.z)
  8581. min.z = v.z;
  8582. if (v.x > max.x)
  8583. max.x = v.x;
  8584. if (v.y > max.y)
  8585. max.y = v.y;
  8586. if (v.z > max.z)
  8587. max.z = v.z;
  8588. };
  8589. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8590. for (var prop in source) {
  8591. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8592. continue;
  8593. }
  8594. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8595. continue;
  8596. }
  8597. var sourceValue = source[prop];
  8598. var typeOfSourceValue = typeof sourceValue;
  8599. if (typeOfSourceValue === "function") {
  8600. continue;
  8601. }
  8602. try {
  8603. if (typeOfSourceValue === "object") {
  8604. if (sourceValue instanceof Array) {
  8605. destination[prop] = [];
  8606. if (sourceValue.length > 0) {
  8607. if (typeof sourceValue[0] == "object") {
  8608. for (var index = 0; index < sourceValue.length; index++) {
  8609. var clonedValue = cloneValue(sourceValue[index], destination);
  8610. if (destination[prop].indexOf(clonedValue) === -1) {
  8611. destination[prop].push(clonedValue);
  8612. }
  8613. }
  8614. }
  8615. else {
  8616. destination[prop] = sourceValue.slice(0);
  8617. }
  8618. }
  8619. }
  8620. else {
  8621. destination[prop] = cloneValue(sourceValue, destination);
  8622. }
  8623. }
  8624. else {
  8625. destination[prop] = sourceValue;
  8626. }
  8627. }
  8628. catch (e) {
  8629. // Just ignore error (it could be because of a read-only property)
  8630. }
  8631. }
  8632. };
  8633. Tools.IsEmpty = function (obj) {
  8634. for (var i in obj) {
  8635. if (obj.hasOwnProperty(i)) {
  8636. return false;
  8637. }
  8638. }
  8639. return true;
  8640. };
  8641. Tools.RegisterTopRootEvents = function (events) {
  8642. for (var index = 0; index < events.length; index++) {
  8643. var event = events[index];
  8644. window.addEventListener(event.name, event.handler, false);
  8645. try {
  8646. if (window.parent) {
  8647. window.parent.addEventListener(event.name, event.handler, false);
  8648. }
  8649. }
  8650. catch (e) {
  8651. // Silently fails...
  8652. }
  8653. }
  8654. };
  8655. Tools.UnregisterTopRootEvents = function (events) {
  8656. for (var index = 0; index < events.length; index++) {
  8657. var event = events[index];
  8658. window.removeEventListener(event.name, event.handler);
  8659. try {
  8660. if (window.parent) {
  8661. window.parent.removeEventListener(event.name, event.handler);
  8662. }
  8663. }
  8664. catch (e) {
  8665. // Silently fails...
  8666. }
  8667. }
  8668. };
  8669. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8670. if (mimeType === void 0) { mimeType = "image/png"; }
  8671. // Read the contents of the framebuffer
  8672. var numberOfChannelsByLine = width * 4;
  8673. var halfHeight = height / 2;
  8674. //Reading datas from WebGL
  8675. var data = engine.readPixels(0, 0, width, height);
  8676. //To flip image on Y axis.
  8677. for (var i = 0; i < halfHeight; i++) {
  8678. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8679. var currentCell = j + i * numberOfChannelsByLine;
  8680. var targetLine = height - i - 1;
  8681. var targetCell = j + targetLine * numberOfChannelsByLine;
  8682. var temp = data[currentCell];
  8683. data[currentCell] = data[targetCell];
  8684. data[targetCell] = temp;
  8685. }
  8686. }
  8687. // Create a 2D canvas to store the result
  8688. if (!screenshotCanvas) {
  8689. screenshotCanvas = document.createElement('canvas');
  8690. }
  8691. screenshotCanvas.width = width;
  8692. screenshotCanvas.height = height;
  8693. var context = screenshotCanvas.getContext('2d');
  8694. if (context) {
  8695. // Copy the pixels to a 2D canvas
  8696. var imageData = context.createImageData(width, height);
  8697. var castData = (imageData.data);
  8698. castData.set(data);
  8699. context.putImageData(imageData, 0, 0);
  8700. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8701. }
  8702. };
  8703. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8704. if (mimeType === void 0) { mimeType = "image/png"; }
  8705. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8706. if (successCallback) {
  8707. successCallback(base64Image);
  8708. }
  8709. else {
  8710. // We need HTMLCanvasElement.toBlob for HD screenshots
  8711. if (!screenshotCanvas.toBlob) {
  8712. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8713. screenshotCanvas.toBlob = function (callback, type, quality) {
  8714. var _this = this;
  8715. setTimeout(function () {
  8716. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8717. for (var i = 0; i < len; i++) {
  8718. arr[i] = binStr.charCodeAt(i);
  8719. }
  8720. callback(new Blob([arr], { type: type || 'image/png' }));
  8721. });
  8722. };
  8723. }
  8724. screenshotCanvas.toBlob(function (blob) {
  8725. var url = URL.createObjectURL(blob);
  8726. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8727. if (("download" in document.createElement("a"))) {
  8728. var a = window.document.createElement("a");
  8729. a.href = url;
  8730. if (fileName) {
  8731. a.setAttribute("download", fileName);
  8732. }
  8733. else {
  8734. var date = new Date();
  8735. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8736. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8737. }
  8738. window.document.body.appendChild(a);
  8739. a.addEventListener("click", function () {
  8740. if (a.parentElement) {
  8741. a.parentElement.removeChild(a);
  8742. }
  8743. });
  8744. a.click();
  8745. }
  8746. else {
  8747. var newWindow = window.open("");
  8748. if (!newWindow)
  8749. return;
  8750. var img = newWindow.document.createElement("img");
  8751. img.onload = function () {
  8752. // no longer need to read the blob so it's revoked
  8753. URL.revokeObjectURL(url);
  8754. };
  8755. img.src = url;
  8756. newWindow.document.body.appendChild(img);
  8757. }
  8758. });
  8759. }
  8760. };
  8761. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8762. if (mimeType === void 0) { mimeType = "image/png"; }
  8763. var width;
  8764. var height;
  8765. // If a precision value is specified
  8766. if (size.precision) {
  8767. width = Math.round(engine.getRenderWidth() * size.precision);
  8768. height = Math.round(width / engine.getAspectRatio(camera));
  8769. }
  8770. else if (size.width && size.height) {
  8771. width = size.width;
  8772. height = size.height;
  8773. }
  8774. else if (size.width && !size.height) {
  8775. width = size.width;
  8776. height = Math.round(width / engine.getAspectRatio(camera));
  8777. }
  8778. else if (size.height && !size.width) {
  8779. height = size.height;
  8780. width = Math.round(height * engine.getAspectRatio(camera));
  8781. }
  8782. else if (!isNaN(size)) {
  8783. height = size;
  8784. width = size;
  8785. }
  8786. else {
  8787. Tools.Error("Invalid 'size' parameter !");
  8788. return;
  8789. }
  8790. if (!screenshotCanvas) {
  8791. screenshotCanvas = document.createElement('canvas');
  8792. }
  8793. screenshotCanvas.width = width;
  8794. screenshotCanvas.height = height;
  8795. var renderContext = screenshotCanvas.getContext("2d");
  8796. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8797. var newWidth = width;
  8798. var newHeight = newWidth / ratio;
  8799. if (newHeight > height) {
  8800. newHeight = height;
  8801. newWidth = newHeight * ratio;
  8802. }
  8803. var offsetX = Math.max(0, width - newWidth) / 2;
  8804. var offsetY = Math.max(0, height - newHeight) / 2;
  8805. var renderingCanvas = engine.getRenderingCanvas();
  8806. if (renderContext && renderingCanvas) {
  8807. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8808. }
  8809. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8810. };
  8811. /**
  8812. * Generates an image screenshot from the specified camera.
  8813. *
  8814. * @param engine The engine to use for rendering
  8815. * @param camera The camera to use for rendering
  8816. * @param size This parameter can be set to a single number or to an object with the
  8817. * following (optional) properties: precision, width, height. If a single number is passed,
  8818. * it will be used for both width and height. If an object is passed, the screenshot size
  8819. * will be derived from the parameters. The precision property is a multiplier allowing
  8820. * rendering at a higher or lower resolution.
  8821. * @param successCallback The callback receives a single parameter which contains the
  8822. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8823. * src parameter of an <img> to display it.
  8824. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8825. * Check your browser for supported MIME types.
  8826. * @param samples Texture samples (default: 1)
  8827. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8828. * @param fileName A name for for the downloaded file.
  8829. * @constructor
  8830. */
  8831. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8832. if (mimeType === void 0) { mimeType = "image/png"; }
  8833. if (samples === void 0) { samples = 1; }
  8834. if (antialiasing === void 0) { antialiasing = false; }
  8835. var width;
  8836. var height;
  8837. //If a precision value is specified
  8838. if (size.precision) {
  8839. width = Math.round(engine.getRenderWidth() * size.precision);
  8840. height = Math.round(width / engine.getAspectRatio(camera));
  8841. size = { width: width, height: height };
  8842. }
  8843. else if (size.width && size.height) {
  8844. width = size.width;
  8845. height = size.height;
  8846. }
  8847. else if (size.width && !size.height) {
  8848. width = size.width;
  8849. height = Math.round(width / engine.getAspectRatio(camera));
  8850. size = { width: width, height: height };
  8851. }
  8852. else if (size.height && !size.width) {
  8853. height = size.height;
  8854. width = Math.round(height * engine.getAspectRatio(camera));
  8855. size = { width: width, height: height };
  8856. }
  8857. else if (!isNaN(size)) {
  8858. height = size;
  8859. width = size;
  8860. }
  8861. else {
  8862. Tools.Error("Invalid 'size' parameter !");
  8863. return;
  8864. }
  8865. var scene = camera.getScene();
  8866. var previousCamera = null;
  8867. if (scene.activeCamera !== camera) {
  8868. previousCamera = scene.activeCamera;
  8869. scene.activeCamera = camera;
  8870. }
  8871. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8872. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8873. texture.renderList = null;
  8874. texture.samples = samples;
  8875. if (antialiasing) {
  8876. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8877. }
  8878. texture.onAfterRenderObservable.add(function () {
  8879. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8880. });
  8881. scene.incrementRenderId();
  8882. scene.resetCachedMaterial();
  8883. texture.render(true);
  8884. texture.dispose();
  8885. if (previousCamera) {
  8886. scene.activeCamera = previousCamera;
  8887. }
  8888. camera.getProjectionMatrix(true); // Force cache refresh;
  8889. };
  8890. // XHR response validator for local file scenario
  8891. Tools.ValidateXHRData = function (xhr, dataType) {
  8892. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8893. if (dataType === void 0) { dataType = 7; }
  8894. try {
  8895. if (dataType & 1) {
  8896. if (xhr.responseText && xhr.responseText.length > 0) {
  8897. return true;
  8898. }
  8899. else if (dataType === 1) {
  8900. return false;
  8901. }
  8902. }
  8903. if (dataType & 2) {
  8904. // Check header width and height since there is no "TGA" magic number
  8905. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8906. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8907. return true;
  8908. }
  8909. else if (dataType === 2) {
  8910. return false;
  8911. }
  8912. }
  8913. if (dataType & 4) {
  8914. // Check for the "DDS" magic number
  8915. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8916. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8917. return true;
  8918. }
  8919. else {
  8920. return false;
  8921. }
  8922. }
  8923. }
  8924. catch (e) {
  8925. // Global protection
  8926. }
  8927. return false;
  8928. };
  8929. /**
  8930. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8931. * Be aware Math.random() could cause collisions, but:
  8932. * "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"
  8933. */
  8934. Tools.RandomId = function () {
  8935. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8936. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8937. return v.toString(16);
  8938. });
  8939. };
  8940. /**
  8941. * Test if the given uri is a base64 string.
  8942. * @param uri The uri to test
  8943. * @return True if the uri is a base64 string or false otherwise.
  8944. */
  8945. Tools.IsBase64 = function (uri) {
  8946. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8947. };
  8948. /**
  8949. * Decode the given base64 uri.
  8950. * @param uri The uri to decode
  8951. * @return The decoded base64 data.
  8952. */
  8953. Tools.DecodeBase64 = function (uri) {
  8954. var decodedString = atob(uri.split(",")[1]);
  8955. var bufferLength = decodedString.length;
  8956. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8957. for (var i = 0; i < bufferLength; i++) {
  8958. bufferView[i] = decodedString.charCodeAt(i);
  8959. }
  8960. return bufferView.buffer;
  8961. };
  8962. Object.defineProperty(Tools, "NoneLogLevel", {
  8963. get: function () {
  8964. return Tools._NoneLogLevel;
  8965. },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. Object.defineProperty(Tools, "MessageLogLevel", {
  8970. get: function () {
  8971. return Tools._MessageLogLevel;
  8972. },
  8973. enumerable: true,
  8974. configurable: true
  8975. });
  8976. Object.defineProperty(Tools, "WarningLogLevel", {
  8977. get: function () {
  8978. return Tools._WarningLogLevel;
  8979. },
  8980. enumerable: true,
  8981. configurable: true
  8982. });
  8983. Object.defineProperty(Tools, "ErrorLogLevel", {
  8984. get: function () {
  8985. return Tools._ErrorLogLevel;
  8986. },
  8987. enumerable: true,
  8988. configurable: true
  8989. });
  8990. Object.defineProperty(Tools, "AllLogLevel", {
  8991. get: function () {
  8992. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8993. },
  8994. enumerable: true,
  8995. configurable: true
  8996. });
  8997. Tools._AddLogEntry = function (entry) {
  8998. Tools._LogCache = entry + Tools._LogCache;
  8999. if (Tools.OnNewCacheEntry) {
  9000. Tools.OnNewCacheEntry(entry);
  9001. }
  9002. };
  9003. Tools._FormatMessage = function (message) {
  9004. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9005. var date = new Date();
  9006. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9007. };
  9008. Tools._LogDisabled = function (message) {
  9009. // nothing to do
  9010. };
  9011. Tools._LogEnabled = function (message) {
  9012. var formattedMessage = Tools._FormatMessage(message);
  9013. console.log("BJS - " + formattedMessage);
  9014. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9015. Tools._AddLogEntry(entry);
  9016. };
  9017. Tools._WarnDisabled = function (message) {
  9018. // nothing to do
  9019. };
  9020. Tools._WarnEnabled = function (message) {
  9021. var formattedMessage = Tools._FormatMessage(message);
  9022. console.warn("BJS - " + formattedMessage);
  9023. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9024. Tools._AddLogEntry(entry);
  9025. };
  9026. Tools._ErrorDisabled = function (message) {
  9027. // nothing to do
  9028. };
  9029. Tools._ErrorEnabled = function (message) {
  9030. Tools.errorsCount++;
  9031. var formattedMessage = Tools._FormatMessage(message);
  9032. console.error("BJS - " + formattedMessage);
  9033. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9034. Tools._AddLogEntry(entry);
  9035. };
  9036. Object.defineProperty(Tools, "LogCache", {
  9037. get: function () {
  9038. return Tools._LogCache;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Tools.ClearLogCache = function () {
  9044. Tools._LogCache = "";
  9045. Tools.errorsCount = 0;
  9046. };
  9047. Object.defineProperty(Tools, "LogLevels", {
  9048. set: function (level) {
  9049. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9050. Tools.Log = Tools._LogEnabled;
  9051. }
  9052. else {
  9053. Tools.Log = Tools._LogDisabled;
  9054. }
  9055. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9056. Tools.Warn = Tools._WarnEnabled;
  9057. }
  9058. else {
  9059. Tools.Warn = Tools._WarnDisabled;
  9060. }
  9061. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9062. Tools.Error = Tools._ErrorEnabled;
  9063. }
  9064. else {
  9065. Tools.Error = Tools._ErrorDisabled;
  9066. }
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Tools.IsWindowObjectExist = function () {
  9072. return (typeof window) !== "undefined";
  9073. };
  9074. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9075. get: function () {
  9076. return Tools._PerformanceNoneLogLevel;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9082. get: function () {
  9083. return Tools._PerformanceUserMarkLogLevel;
  9084. },
  9085. enumerable: true,
  9086. configurable: true
  9087. });
  9088. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9089. get: function () {
  9090. return Tools._PerformanceConsoleLogLevel;
  9091. },
  9092. enumerable: true,
  9093. configurable: true
  9094. });
  9095. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9096. set: function (level) {
  9097. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9098. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9099. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9100. return;
  9101. }
  9102. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9103. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9104. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9105. return;
  9106. }
  9107. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9108. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9114. };
  9115. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9116. };
  9117. Tools._StartUserMark = function (counterName, condition) {
  9118. if (condition === void 0) { condition = true; }
  9119. if (!Tools._performance) {
  9120. if (!Tools.IsWindowObjectExist()) {
  9121. return;
  9122. }
  9123. Tools._performance = window.performance;
  9124. }
  9125. if (!condition || !Tools._performance.mark) {
  9126. return;
  9127. }
  9128. Tools._performance.mark(counterName + "-Begin");
  9129. };
  9130. Tools._EndUserMark = function (counterName, condition) {
  9131. if (condition === void 0) { condition = true; }
  9132. if (!condition || !Tools._performance.mark) {
  9133. return;
  9134. }
  9135. Tools._performance.mark(counterName + "-End");
  9136. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9137. };
  9138. Tools._StartPerformanceConsole = function (counterName, condition) {
  9139. if (condition === void 0) { condition = true; }
  9140. if (!condition) {
  9141. return;
  9142. }
  9143. Tools._StartUserMark(counterName, condition);
  9144. if (console.time) {
  9145. console.time(counterName);
  9146. }
  9147. };
  9148. Tools._EndPerformanceConsole = function (counterName, condition) {
  9149. if (condition === void 0) { condition = true; }
  9150. if (!condition) {
  9151. return;
  9152. }
  9153. Tools._EndUserMark(counterName, condition);
  9154. if (console.time) {
  9155. console.timeEnd(counterName);
  9156. }
  9157. };
  9158. Object.defineProperty(Tools, "Now", {
  9159. get: function () {
  9160. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9161. return window.performance.now();
  9162. }
  9163. return new Date().getTime();
  9164. },
  9165. enumerable: true,
  9166. configurable: true
  9167. });
  9168. /**
  9169. * This method will return the name of the class used to create the instance of the given object.
  9170. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9171. * @param object the object to get the class name from
  9172. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9173. */
  9174. Tools.GetClassName = function (object, isType) {
  9175. if (isType === void 0) { isType = false; }
  9176. var name = null;
  9177. if (!isType && object.getClassName) {
  9178. name = object.getClassName();
  9179. }
  9180. else {
  9181. if (object instanceof Object) {
  9182. var classObj = isType ? object : Object.getPrototypeOf(object);
  9183. name = classObj.constructor["__bjsclassName__"];
  9184. }
  9185. if (!name) {
  9186. name = typeof object;
  9187. }
  9188. }
  9189. return name;
  9190. };
  9191. Tools.First = function (array, predicate) {
  9192. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9193. var el = array_1[_i];
  9194. if (predicate(el)) {
  9195. return el;
  9196. }
  9197. }
  9198. return null;
  9199. };
  9200. /**
  9201. * This method will return the name of the full name of the class, including its owning module (if any).
  9202. * 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).
  9203. * @param object the object to get the class name from
  9204. * @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.
  9205. */
  9206. Tools.getFullClassName = function (object, isType) {
  9207. if (isType === void 0) { isType = false; }
  9208. var className = null;
  9209. var moduleName = null;
  9210. if (!isType && object.getClassName) {
  9211. className = object.getClassName();
  9212. }
  9213. else {
  9214. if (object instanceof Object) {
  9215. var classObj = isType ? object : Object.getPrototypeOf(object);
  9216. className = classObj.constructor["__bjsclassName__"];
  9217. moduleName = classObj.constructor["__bjsmoduleName__"];
  9218. }
  9219. if (!className) {
  9220. className = typeof object;
  9221. }
  9222. }
  9223. if (!className) {
  9224. return null;
  9225. }
  9226. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9227. };
  9228. /**
  9229. * 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.
  9230. * @param array
  9231. */
  9232. Tools.arrayOrStringFeeder = function (array) {
  9233. return function (index) {
  9234. if (index >= array.length) {
  9235. return null;
  9236. }
  9237. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9238. if (val && val.getHashCode) {
  9239. val = val.getHashCode();
  9240. }
  9241. if (typeof val === "string") {
  9242. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9243. }
  9244. return val;
  9245. };
  9246. };
  9247. /**
  9248. * Compute the hashCode of a stream of number
  9249. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9250. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9251. * @return the hash code computed
  9252. */
  9253. Tools.hashCodeFromStream = function (feeder) {
  9254. // Based from here: http://stackoverflow.com/a/7616484/802124
  9255. var hash = 0;
  9256. var index = 0;
  9257. var chr = feeder(index++);
  9258. while (chr != null) {
  9259. hash = ((hash << 5) - hash) + chr;
  9260. hash |= 0; // Convert to 32bit integer
  9261. chr = feeder(index++);
  9262. }
  9263. return hash;
  9264. };
  9265. /**
  9266. * Returns a promise that resolves after the given amount of time.
  9267. * @param delay Number of milliseconds to delay
  9268. * @returns Promise that resolves after the given amount of time
  9269. */
  9270. Tools.DelayAsync = function (delay) {
  9271. return new Promise(function (resolve) {
  9272. setTimeout(function () {
  9273. resolve();
  9274. }, delay);
  9275. });
  9276. };
  9277. Tools.BaseUrl = "";
  9278. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9279. /**
  9280. * Default behaviour for cors in the application.
  9281. * It can be a string if the expected behavior is identical in the entire app.
  9282. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9283. */
  9284. Tools.CorsBehavior = "anonymous";
  9285. Tools.UseFallbackTexture = true;
  9286. /**
  9287. * Use this object to register external classes like custom textures or material
  9288. * to allow the laoders to instantiate them
  9289. */
  9290. Tools.RegisteredExternalClasses = {};
  9291. // Used in case of a texture loading problem
  9292. 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";
  9293. Tools.PreprocessUrl = function (url) {
  9294. return url;
  9295. };
  9296. // Logs
  9297. Tools._NoneLogLevel = 0;
  9298. Tools._MessageLogLevel = 1;
  9299. Tools._WarningLogLevel = 2;
  9300. Tools._ErrorLogLevel = 4;
  9301. Tools._LogCache = "";
  9302. Tools.errorsCount = 0;
  9303. Tools.Log = Tools._LogEnabled;
  9304. Tools.Warn = Tools._WarnEnabled;
  9305. Tools.Error = Tools._ErrorEnabled;
  9306. // Performances
  9307. Tools._PerformanceNoneLogLevel = 0;
  9308. Tools._PerformanceUserMarkLogLevel = 1;
  9309. Tools._PerformanceConsoleLogLevel = 2;
  9310. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9311. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9312. return Tools;
  9313. }());
  9314. BABYLON.Tools = Tools;
  9315. /**
  9316. * This class is used to track a performance counter which is number based.
  9317. * The user has access to many properties which give statistics of different nature
  9318. *
  9319. * The implementer can track two kinds of Performance Counter: time and count
  9320. * 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.
  9321. * 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.
  9322. */
  9323. var PerfCounter = /** @class */ (function () {
  9324. function PerfCounter() {
  9325. this._startMonitoringTime = 0;
  9326. this._min = 0;
  9327. this._max = 0;
  9328. this._average = 0;
  9329. this._lastSecAverage = 0;
  9330. this._current = 0;
  9331. this._totalValueCount = 0;
  9332. this._totalAccumulated = 0;
  9333. this._lastSecAccumulated = 0;
  9334. this._lastSecTime = 0;
  9335. this._lastSecValueCount = 0;
  9336. }
  9337. Object.defineProperty(PerfCounter.prototype, "min", {
  9338. /**
  9339. * Returns the smallest value ever
  9340. */
  9341. get: function () {
  9342. return this._min;
  9343. },
  9344. enumerable: true,
  9345. configurable: true
  9346. });
  9347. Object.defineProperty(PerfCounter.prototype, "max", {
  9348. /**
  9349. * Returns the biggest value ever
  9350. */
  9351. get: function () {
  9352. return this._max;
  9353. },
  9354. enumerable: true,
  9355. configurable: true
  9356. });
  9357. Object.defineProperty(PerfCounter.prototype, "average", {
  9358. /**
  9359. * Returns the average value since the performance counter is running
  9360. */
  9361. get: function () {
  9362. return this._average;
  9363. },
  9364. enumerable: true,
  9365. configurable: true
  9366. });
  9367. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9368. /**
  9369. * Returns the average value of the last second the counter was monitored
  9370. */
  9371. get: function () {
  9372. return this._lastSecAverage;
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. Object.defineProperty(PerfCounter.prototype, "current", {
  9378. /**
  9379. * Returns the current value
  9380. */
  9381. get: function () {
  9382. return this._current;
  9383. },
  9384. enumerable: true,
  9385. configurable: true
  9386. });
  9387. Object.defineProperty(PerfCounter.prototype, "total", {
  9388. get: function () {
  9389. return this._totalAccumulated;
  9390. },
  9391. enumerable: true,
  9392. configurable: true
  9393. });
  9394. Object.defineProperty(PerfCounter.prototype, "count", {
  9395. get: function () {
  9396. return this._totalValueCount;
  9397. },
  9398. enumerable: true,
  9399. configurable: true
  9400. });
  9401. /**
  9402. * Call this method to start monitoring a new frame.
  9403. * 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.
  9404. */
  9405. PerfCounter.prototype.fetchNewFrame = function () {
  9406. this._totalValueCount++;
  9407. this._current = 0;
  9408. this._lastSecValueCount++;
  9409. };
  9410. /**
  9411. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9412. * @param newCount the count value to add to the monitored count
  9413. * @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.
  9414. */
  9415. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9416. if (!PerfCounter.Enabled) {
  9417. return;
  9418. }
  9419. this._current += newCount;
  9420. if (fetchResult) {
  9421. this._fetchResult();
  9422. }
  9423. };
  9424. /**
  9425. * Start monitoring this performance counter
  9426. */
  9427. PerfCounter.prototype.beginMonitoring = function () {
  9428. if (!PerfCounter.Enabled) {
  9429. return;
  9430. }
  9431. this._startMonitoringTime = Tools.Now;
  9432. };
  9433. /**
  9434. * Compute the time lapsed since the previous beginMonitoring() call.
  9435. * @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
  9436. */
  9437. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9438. if (newFrame === void 0) { newFrame = true; }
  9439. if (!PerfCounter.Enabled) {
  9440. return;
  9441. }
  9442. if (newFrame) {
  9443. this.fetchNewFrame();
  9444. }
  9445. var currentTime = Tools.Now;
  9446. this._current = currentTime - this._startMonitoringTime;
  9447. if (newFrame) {
  9448. this._fetchResult();
  9449. }
  9450. };
  9451. PerfCounter.prototype._fetchResult = function () {
  9452. this._totalAccumulated += this._current;
  9453. this._lastSecAccumulated += this._current;
  9454. // Min/Max update
  9455. this._min = Math.min(this._min, this._current);
  9456. this._max = Math.max(this._max, this._current);
  9457. this._average = this._totalAccumulated / this._totalValueCount;
  9458. // Reset last sec?
  9459. var now = Tools.Now;
  9460. if ((now - this._lastSecTime) > 1000) {
  9461. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9462. this._lastSecTime = now;
  9463. this._lastSecAccumulated = 0;
  9464. this._lastSecValueCount = 0;
  9465. }
  9466. };
  9467. PerfCounter.Enabled = true;
  9468. return PerfCounter;
  9469. }());
  9470. BABYLON.PerfCounter = PerfCounter;
  9471. /**
  9472. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9473. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9474. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9475. * @param name The name of the class, case should be preserved
  9476. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9477. */
  9478. function className(name, module) {
  9479. return function (target) {
  9480. target["__bjsclassName__"] = name;
  9481. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9482. };
  9483. }
  9484. BABYLON.className = className;
  9485. /**
  9486. * An implementation of a loop for asynchronous functions.
  9487. */
  9488. var AsyncLoop = /** @class */ (function () {
  9489. /**
  9490. * Constroctor.
  9491. * @param iterations the number of iterations.
  9492. * @param _fn the function to run each iteration
  9493. * @param _successCallback the callback that will be called upon succesful execution
  9494. * @param offset starting offset.
  9495. */
  9496. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9497. if (offset === void 0) { offset = 0; }
  9498. this.iterations = iterations;
  9499. this._fn = _fn;
  9500. this._successCallback = _successCallback;
  9501. this.index = offset - 1;
  9502. this._done = false;
  9503. }
  9504. /**
  9505. * Execute the next iteration. Must be called after the last iteration was finished.
  9506. */
  9507. AsyncLoop.prototype.executeNext = function () {
  9508. if (!this._done) {
  9509. if (this.index + 1 < this.iterations) {
  9510. ++this.index;
  9511. this._fn(this);
  9512. }
  9513. else {
  9514. this.breakLoop();
  9515. }
  9516. }
  9517. };
  9518. /**
  9519. * Break the loop and run the success callback.
  9520. */
  9521. AsyncLoop.prototype.breakLoop = function () {
  9522. this._done = true;
  9523. this._successCallback();
  9524. };
  9525. /**
  9526. * Helper function
  9527. */
  9528. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9529. if (offset === void 0) { offset = 0; }
  9530. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9531. loop.executeNext();
  9532. return loop;
  9533. };
  9534. /**
  9535. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9536. * @param iterations total number of iterations
  9537. * @param syncedIterations number of synchronous iterations in each async iteration.
  9538. * @param fn the function to call each iteration.
  9539. * @param callback a success call back that will be called when iterating stops.
  9540. * @param breakFunction a break condition (optional)
  9541. * @param timeout timeout settings for the setTimeout function. default - 0.
  9542. * @constructor
  9543. */
  9544. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9545. if (timeout === void 0) { timeout = 0; }
  9546. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9547. if (breakFunction && breakFunction())
  9548. loop.breakLoop();
  9549. else {
  9550. setTimeout(function () {
  9551. for (var i = 0; i < syncedIterations; ++i) {
  9552. var iteration = (loop.index * syncedIterations) + i;
  9553. if (iteration >= iterations)
  9554. break;
  9555. fn(iteration);
  9556. if (breakFunction && breakFunction()) {
  9557. loop.breakLoop();
  9558. break;
  9559. }
  9560. }
  9561. loop.executeNext();
  9562. }, timeout);
  9563. }
  9564. }, callback);
  9565. };
  9566. return AsyncLoop;
  9567. }());
  9568. BABYLON.AsyncLoop = AsyncLoop;
  9569. })(BABYLON || (BABYLON = {}));
  9570. //# sourceMappingURL=babylon.tools.js.map
  9571. "use strict";
  9572. var BABYLON;
  9573. (function (BABYLON) {
  9574. var PromiseStates;
  9575. (function (PromiseStates) {
  9576. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9577. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9578. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9579. })(PromiseStates || (PromiseStates = {}));
  9580. var FulFillmentAgregator = /** @class */ (function () {
  9581. function FulFillmentAgregator() {
  9582. this.count = 0;
  9583. this.target = 0;
  9584. this.results = [];
  9585. }
  9586. return FulFillmentAgregator;
  9587. }());
  9588. var InternalPromise = /** @class */ (function () {
  9589. function InternalPromise(resolver) {
  9590. var _this = this;
  9591. this._state = PromiseStates.Pending;
  9592. this._children = new Array();
  9593. this._rejectWasConsumed = false;
  9594. if (!resolver) {
  9595. return;
  9596. }
  9597. try {
  9598. resolver(function (value) {
  9599. _this._resolve(value);
  9600. }, function (reason) {
  9601. _this._reject(reason);
  9602. });
  9603. }
  9604. catch (e) {
  9605. this._reject(e);
  9606. }
  9607. }
  9608. InternalPromise.prototype.catch = function (onRejected) {
  9609. return this.then(undefined, onRejected);
  9610. };
  9611. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9612. var _this = this;
  9613. var newPromise = new InternalPromise();
  9614. newPromise._onFulfilled = onFulfilled;
  9615. newPromise._onRejected = onRejected;
  9616. // Composition
  9617. this._children.push(newPromise);
  9618. if (this._state !== PromiseStates.Pending) {
  9619. BABYLON.Tools.SetImmediate(function () {
  9620. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9621. var returnedValue = newPromise._resolve(_this._result);
  9622. if (returnedValue !== undefined && returnedValue !== null) {
  9623. if (returnedValue._state !== undefined) {
  9624. var returnedPromise = returnedValue;
  9625. newPromise._children.push(returnedPromise);
  9626. newPromise = returnedPromise;
  9627. }
  9628. else {
  9629. newPromise._result = returnedValue;
  9630. }
  9631. }
  9632. }
  9633. else {
  9634. newPromise._reject(_this._reason);
  9635. }
  9636. });
  9637. }
  9638. return newPromise;
  9639. };
  9640. InternalPromise.prototype._moveChildren = function (children) {
  9641. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9642. if (this._state === PromiseStates.Fulfilled) {
  9643. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9644. var child = _b[_i];
  9645. child._resolve(this._result);
  9646. }
  9647. }
  9648. else if (this._state === PromiseStates.Rejected) {
  9649. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9650. var child = _d[_c];
  9651. child._reject(this._reason);
  9652. }
  9653. }
  9654. var _a;
  9655. };
  9656. InternalPromise.prototype._resolve = function (value) {
  9657. try {
  9658. this._state = PromiseStates.Fulfilled;
  9659. var returnedValue = null;
  9660. if (this._onFulfilled) {
  9661. returnedValue = this._onFulfilled(value);
  9662. }
  9663. if (returnedValue !== undefined && returnedValue !== null) {
  9664. if (returnedValue._state !== undefined) {
  9665. // Transmit children
  9666. var returnedPromise = returnedValue;
  9667. returnedPromise._moveChildren(this._children);
  9668. value = returnedPromise._result;
  9669. }
  9670. else {
  9671. value = returnedValue;
  9672. }
  9673. }
  9674. this._result = value;
  9675. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9676. var child = _a[_i];
  9677. child._resolve(value);
  9678. }
  9679. this._children.length = 0;
  9680. delete this._onFulfilled;
  9681. delete this._onRejected;
  9682. }
  9683. catch (e) {
  9684. this._reject(e, true);
  9685. }
  9686. };
  9687. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9688. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9689. this._state = PromiseStates.Rejected;
  9690. this._reason = reason;
  9691. if (this._onRejected && !onLocalThrow) {
  9692. try {
  9693. this._onRejected(reason);
  9694. this._rejectWasConsumed = true;
  9695. }
  9696. catch (e) {
  9697. reason = e;
  9698. }
  9699. }
  9700. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9701. var child = _a[_i];
  9702. if (this._rejectWasConsumed) {
  9703. child._resolve(null);
  9704. }
  9705. else {
  9706. child._reject(reason);
  9707. }
  9708. }
  9709. this._children.length = 0;
  9710. delete this._onFulfilled;
  9711. delete this._onRejected;
  9712. };
  9713. InternalPromise.resolve = function (value) {
  9714. var newPromise = new InternalPromise();
  9715. newPromise._resolve(value);
  9716. return newPromise;
  9717. };
  9718. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9719. promise.then(function (value) {
  9720. agregator.results[index] = value;
  9721. agregator.count++;
  9722. if (agregator.count === agregator.target) {
  9723. agregator.rootPromise._resolve(agregator.results);
  9724. }
  9725. return null;
  9726. }, function (reason) {
  9727. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9728. agregator.rootPromise._reject(reason);
  9729. }
  9730. });
  9731. };
  9732. InternalPromise.all = function (promises) {
  9733. var newPromise = new InternalPromise();
  9734. var agregator = new FulFillmentAgregator();
  9735. agregator.target = promises.length;
  9736. agregator.rootPromise = newPromise;
  9737. if (promises.length) {
  9738. for (var index = 0; index < promises.length; index++) {
  9739. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9740. }
  9741. }
  9742. else {
  9743. newPromise._resolve([]);
  9744. }
  9745. return newPromise;
  9746. };
  9747. InternalPromise.race = function (promises) {
  9748. var newPromise = new InternalPromise();
  9749. if (promises.length) {
  9750. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9751. var promise = promises_1[_i];
  9752. promise.then(function (value) {
  9753. if (newPromise) {
  9754. newPromise._resolve(value);
  9755. newPromise = null;
  9756. }
  9757. return null;
  9758. }, function (reason) {
  9759. if (newPromise) {
  9760. newPromise._reject(reason);
  9761. newPromise = null;
  9762. }
  9763. });
  9764. }
  9765. }
  9766. return newPromise;
  9767. };
  9768. return InternalPromise;
  9769. }());
  9770. /**
  9771. * Helper class that provides a small promise polyfill
  9772. */
  9773. var PromisePolyfill = /** @class */ (function () {
  9774. function PromisePolyfill() {
  9775. }
  9776. /**
  9777. * Static function used to check if the polyfill is required
  9778. * If this is the case then the function will inject the polyfill to window.Promise
  9779. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9780. */
  9781. PromisePolyfill.Apply = function (force) {
  9782. if (force === void 0) { force = false; }
  9783. if (force || typeof Promise === 'undefined') {
  9784. var root = window;
  9785. root.Promise = InternalPromise;
  9786. }
  9787. };
  9788. return PromisePolyfill;
  9789. }());
  9790. BABYLON.PromisePolyfill = PromisePolyfill;
  9791. })(BABYLON || (BABYLON = {}));
  9792. //# sourceMappingURL=babylon.promise.js.map
  9793. "use strict";
  9794. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9795. var BABYLON;
  9796. (function (BABYLON) {
  9797. /**
  9798. * Helper class to push actions to a pool of workers.
  9799. */
  9800. var WorkerPool = /** @class */ (function () {
  9801. /**
  9802. * Constructor
  9803. * @param workers Array of workers to use for actions
  9804. */
  9805. function WorkerPool(workers) {
  9806. this._pendingActions = new Array();
  9807. this._workerInfos = workers.map(function (worker) { return ({
  9808. worker: worker,
  9809. active: false
  9810. }); });
  9811. }
  9812. /**
  9813. * Terminates all workers and clears any pending actions.
  9814. */
  9815. WorkerPool.prototype.dispose = function () {
  9816. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9817. var workerInfo = _a[_i];
  9818. workerInfo.worker.terminate();
  9819. }
  9820. delete this._workerInfos;
  9821. delete this._pendingActions;
  9822. };
  9823. /**
  9824. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9825. * pended until a worker has completed its action.
  9826. * @param action The action to perform. Call onComplete when the action is complete.
  9827. */
  9828. WorkerPool.prototype.push = function (action) {
  9829. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9830. var workerInfo = _a[_i];
  9831. if (!workerInfo.active) {
  9832. this._execute(workerInfo, action);
  9833. return;
  9834. }
  9835. }
  9836. this._pendingActions.push(action);
  9837. };
  9838. WorkerPool.prototype._execute = function (workerInfo, action) {
  9839. var _this = this;
  9840. workerInfo.active = true;
  9841. action(workerInfo.worker, function () {
  9842. workerInfo.active = false;
  9843. var nextAction = _this._pendingActions.shift();
  9844. if (nextAction) {
  9845. _this._execute(workerInfo, nextAction);
  9846. }
  9847. });
  9848. };
  9849. return WorkerPool;
  9850. }());
  9851. BABYLON.WorkerPool = WorkerPool;
  9852. })(BABYLON || (BABYLON = {}));
  9853. //# sourceMappingURL=babylon.workerPool.js.map
  9854. "use strict";
  9855. var BABYLON;
  9856. (function (BABYLON) {
  9857. var _AlphaState = /** @class */ (function () {
  9858. /**
  9859. * Initializes the state.
  9860. */
  9861. function _AlphaState() {
  9862. this._isAlphaBlendDirty = false;
  9863. this._isBlendFunctionParametersDirty = false;
  9864. this._isBlendEquationParametersDirty = false;
  9865. this._isBlendConstantsDirty = false;
  9866. this._alphaBlend = false;
  9867. this._blendFunctionParameters = new Array(4);
  9868. this._blendEquationParameters = new Array(2);
  9869. this._blendConstants = new Array(4);
  9870. this.reset();
  9871. }
  9872. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9873. get: function () {
  9874. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9880. get: function () {
  9881. return this._alphaBlend;
  9882. },
  9883. set: function (value) {
  9884. if (this._alphaBlend === value) {
  9885. return;
  9886. }
  9887. this._alphaBlend = value;
  9888. this._isAlphaBlendDirty = true;
  9889. },
  9890. enumerable: true,
  9891. configurable: true
  9892. });
  9893. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9894. if (this._blendConstants[0] === r &&
  9895. this._blendConstants[1] === g &&
  9896. this._blendConstants[2] === b &&
  9897. this._blendConstants[3] === a) {
  9898. return;
  9899. }
  9900. this._blendConstants[0] = r;
  9901. this._blendConstants[1] = g;
  9902. this._blendConstants[2] = b;
  9903. this._blendConstants[3] = a;
  9904. this._isBlendConstantsDirty = true;
  9905. };
  9906. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9907. if (this._blendFunctionParameters[0] === value0 &&
  9908. this._blendFunctionParameters[1] === value1 &&
  9909. this._blendFunctionParameters[2] === value2 &&
  9910. this._blendFunctionParameters[3] === value3) {
  9911. return;
  9912. }
  9913. this._blendFunctionParameters[0] = value0;
  9914. this._blendFunctionParameters[1] = value1;
  9915. this._blendFunctionParameters[2] = value2;
  9916. this._blendFunctionParameters[3] = value3;
  9917. this._isBlendFunctionParametersDirty = true;
  9918. };
  9919. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9920. if (this._blendEquationParameters[0] === rgb &&
  9921. this._blendEquationParameters[1] === alpha) {
  9922. return;
  9923. }
  9924. this._blendEquationParameters[0] = rgb;
  9925. this._blendEquationParameters[1] = alpha;
  9926. this._isBlendEquationParametersDirty = true;
  9927. };
  9928. _AlphaState.prototype.reset = function () {
  9929. this._alphaBlend = false;
  9930. this._blendFunctionParameters[0] = null;
  9931. this._blendFunctionParameters[1] = null;
  9932. this._blendFunctionParameters[2] = null;
  9933. this._blendFunctionParameters[3] = null;
  9934. this._blendEquationParameters[0] = null;
  9935. this._blendEquationParameters[1] = null;
  9936. this._blendConstants[0] = null;
  9937. this._blendConstants[1] = null;
  9938. this._blendConstants[2] = null;
  9939. this._blendConstants[3] = null;
  9940. this._isAlphaBlendDirty = true;
  9941. this._isBlendFunctionParametersDirty = false;
  9942. this._isBlendEquationParametersDirty = false;
  9943. this._isBlendConstantsDirty = false;
  9944. };
  9945. _AlphaState.prototype.apply = function (gl) {
  9946. if (!this.isDirty) {
  9947. return;
  9948. }
  9949. // Alpha blend
  9950. if (this._isAlphaBlendDirty) {
  9951. if (this._alphaBlend) {
  9952. gl.enable(gl.BLEND);
  9953. }
  9954. else {
  9955. gl.disable(gl.BLEND);
  9956. }
  9957. this._isAlphaBlendDirty = false;
  9958. }
  9959. // Alpha function
  9960. if (this._isBlendFunctionParametersDirty) {
  9961. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9962. this._isBlendFunctionParametersDirty = false;
  9963. }
  9964. // Alpha equation
  9965. if (this._isBlendEquationParametersDirty) {
  9966. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9967. this._isBlendEquationParametersDirty = false;
  9968. }
  9969. // Constants
  9970. if (this._isBlendConstantsDirty) {
  9971. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9972. this._isBlendConstantsDirty = false;
  9973. }
  9974. };
  9975. return _AlphaState;
  9976. }());
  9977. BABYLON._AlphaState = _AlphaState;
  9978. })(BABYLON || (BABYLON = {}));
  9979. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9980. "use strict";
  9981. var BABYLON;
  9982. (function (BABYLON) {
  9983. var _DepthCullingState = /** @class */ (function () {
  9984. /**
  9985. * Initializes the state.
  9986. */
  9987. function _DepthCullingState() {
  9988. this._isDepthTestDirty = false;
  9989. this._isDepthMaskDirty = false;
  9990. this._isDepthFuncDirty = false;
  9991. this._isCullFaceDirty = false;
  9992. this._isCullDirty = false;
  9993. this._isZOffsetDirty = false;
  9994. this._isFrontFaceDirty = false;
  9995. this.reset();
  9996. }
  9997. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9998. get: function () {
  9999. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10005. get: function () {
  10006. return this._zOffset;
  10007. },
  10008. set: function (value) {
  10009. if (this._zOffset === value) {
  10010. return;
  10011. }
  10012. this._zOffset = value;
  10013. this._isZOffsetDirty = true;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10019. get: function () {
  10020. return this._cullFace;
  10021. },
  10022. set: function (value) {
  10023. if (this._cullFace === value) {
  10024. return;
  10025. }
  10026. this._cullFace = value;
  10027. this._isCullFaceDirty = true;
  10028. },
  10029. enumerable: true,
  10030. configurable: true
  10031. });
  10032. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10033. get: function () {
  10034. return this._cull;
  10035. },
  10036. set: function (value) {
  10037. if (this._cull === value) {
  10038. return;
  10039. }
  10040. this._cull = value;
  10041. this._isCullDirty = true;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10047. get: function () {
  10048. return this._depthFunc;
  10049. },
  10050. set: function (value) {
  10051. if (this._depthFunc === value) {
  10052. return;
  10053. }
  10054. this._depthFunc = value;
  10055. this._isDepthFuncDirty = true;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10061. get: function () {
  10062. return this._depthMask;
  10063. },
  10064. set: function (value) {
  10065. if (this._depthMask === value) {
  10066. return;
  10067. }
  10068. this._depthMask = value;
  10069. this._isDepthMaskDirty = true;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10075. get: function () {
  10076. return this._depthTest;
  10077. },
  10078. set: function (value) {
  10079. if (this._depthTest === value) {
  10080. return;
  10081. }
  10082. this._depthTest = value;
  10083. this._isDepthTestDirty = true;
  10084. },
  10085. enumerable: true,
  10086. configurable: true
  10087. });
  10088. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10089. get: function () {
  10090. return this._frontFace;
  10091. },
  10092. set: function (value) {
  10093. if (this._frontFace === value) {
  10094. return;
  10095. }
  10096. this._frontFace = value;
  10097. this._isFrontFaceDirty = true;
  10098. },
  10099. enumerable: true,
  10100. configurable: true
  10101. });
  10102. _DepthCullingState.prototype.reset = function () {
  10103. this._depthMask = true;
  10104. this._depthTest = true;
  10105. this._depthFunc = null;
  10106. this._cullFace = null;
  10107. this._cull = null;
  10108. this._zOffset = 0;
  10109. this._frontFace = null;
  10110. this._isDepthTestDirty = true;
  10111. this._isDepthMaskDirty = true;
  10112. this._isDepthFuncDirty = false;
  10113. this._isCullFaceDirty = false;
  10114. this._isCullDirty = false;
  10115. this._isZOffsetDirty = false;
  10116. this._isFrontFaceDirty = false;
  10117. };
  10118. _DepthCullingState.prototype.apply = function (gl) {
  10119. if (!this.isDirty) {
  10120. return;
  10121. }
  10122. // Cull
  10123. if (this._isCullDirty) {
  10124. if (this.cull) {
  10125. gl.enable(gl.CULL_FACE);
  10126. }
  10127. else {
  10128. gl.disable(gl.CULL_FACE);
  10129. }
  10130. this._isCullDirty = false;
  10131. }
  10132. // Cull face
  10133. if (this._isCullFaceDirty) {
  10134. gl.cullFace(this.cullFace);
  10135. this._isCullFaceDirty = false;
  10136. }
  10137. // Depth mask
  10138. if (this._isDepthMaskDirty) {
  10139. gl.depthMask(this.depthMask);
  10140. this._isDepthMaskDirty = false;
  10141. }
  10142. // Depth test
  10143. if (this._isDepthTestDirty) {
  10144. if (this.depthTest) {
  10145. gl.enable(gl.DEPTH_TEST);
  10146. }
  10147. else {
  10148. gl.disable(gl.DEPTH_TEST);
  10149. }
  10150. this._isDepthTestDirty = false;
  10151. }
  10152. // Depth func
  10153. if (this._isDepthFuncDirty) {
  10154. gl.depthFunc(this.depthFunc);
  10155. this._isDepthFuncDirty = false;
  10156. }
  10157. // zOffset
  10158. if (this._isZOffsetDirty) {
  10159. if (this.zOffset) {
  10160. gl.enable(gl.POLYGON_OFFSET_FILL);
  10161. gl.polygonOffset(this.zOffset, 0);
  10162. }
  10163. else {
  10164. gl.disable(gl.POLYGON_OFFSET_FILL);
  10165. }
  10166. this._isZOffsetDirty = false;
  10167. }
  10168. // Front face
  10169. if (this._isFrontFaceDirty) {
  10170. gl.frontFace(this.frontFace);
  10171. this._isFrontFaceDirty = false;
  10172. }
  10173. };
  10174. return _DepthCullingState;
  10175. }());
  10176. BABYLON._DepthCullingState = _DepthCullingState;
  10177. })(BABYLON || (BABYLON = {}));
  10178. //# sourceMappingURL=babylon.depthCullingState.js.map
  10179. "use strict";
  10180. var BABYLON;
  10181. (function (BABYLON) {
  10182. var _StencilState = /** @class */ (function () {
  10183. function _StencilState() {
  10184. this._isStencilTestDirty = false;
  10185. this._isStencilMaskDirty = false;
  10186. this._isStencilFuncDirty = false;
  10187. this._isStencilOpDirty = false;
  10188. this.reset();
  10189. }
  10190. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10191. get: function () {
  10192. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10193. },
  10194. enumerable: true,
  10195. configurable: true
  10196. });
  10197. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10198. get: function () {
  10199. return this._stencilFunc;
  10200. },
  10201. set: function (value) {
  10202. if (this._stencilFunc === value) {
  10203. return;
  10204. }
  10205. this._stencilFunc = value;
  10206. this._isStencilFuncDirty = true;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10212. get: function () {
  10213. return this._stencilFuncRef;
  10214. },
  10215. set: function (value) {
  10216. if (this._stencilFuncRef === value) {
  10217. return;
  10218. }
  10219. this._stencilFuncRef = value;
  10220. this._isStencilFuncDirty = true;
  10221. },
  10222. enumerable: true,
  10223. configurable: true
  10224. });
  10225. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10226. get: function () {
  10227. return this._stencilFuncMask;
  10228. },
  10229. set: function (value) {
  10230. if (this._stencilFuncMask === value) {
  10231. return;
  10232. }
  10233. this._stencilFuncMask = value;
  10234. this._isStencilFuncDirty = true;
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10240. get: function () {
  10241. return this._stencilOpStencilFail;
  10242. },
  10243. set: function (value) {
  10244. if (this._stencilOpStencilFail === value) {
  10245. return;
  10246. }
  10247. this._stencilOpStencilFail = value;
  10248. this._isStencilOpDirty = true;
  10249. },
  10250. enumerable: true,
  10251. configurable: true
  10252. });
  10253. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10254. get: function () {
  10255. return this._stencilOpDepthFail;
  10256. },
  10257. set: function (value) {
  10258. if (this._stencilOpDepthFail === value) {
  10259. return;
  10260. }
  10261. this._stencilOpDepthFail = value;
  10262. this._isStencilOpDirty = true;
  10263. },
  10264. enumerable: true,
  10265. configurable: true
  10266. });
  10267. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10268. get: function () {
  10269. return this._stencilOpStencilDepthPass;
  10270. },
  10271. set: function (value) {
  10272. if (this._stencilOpStencilDepthPass === value) {
  10273. return;
  10274. }
  10275. this._stencilOpStencilDepthPass = value;
  10276. this._isStencilOpDirty = true;
  10277. },
  10278. enumerable: true,
  10279. configurable: true
  10280. });
  10281. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10282. get: function () {
  10283. return this._stencilMask;
  10284. },
  10285. set: function (value) {
  10286. if (this._stencilMask === value) {
  10287. return;
  10288. }
  10289. this._stencilMask = value;
  10290. this._isStencilMaskDirty = true;
  10291. },
  10292. enumerable: true,
  10293. configurable: true
  10294. });
  10295. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10296. get: function () {
  10297. return this._stencilTest;
  10298. },
  10299. set: function (value) {
  10300. if (this._stencilTest === value) {
  10301. return;
  10302. }
  10303. this._stencilTest = value;
  10304. this._isStencilTestDirty = true;
  10305. },
  10306. enumerable: true,
  10307. configurable: true
  10308. });
  10309. _StencilState.prototype.reset = function () {
  10310. this._stencilTest = false;
  10311. this._stencilMask = 0xFF;
  10312. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10313. this._stencilFuncRef = 1;
  10314. this._stencilFuncMask = 0xFF;
  10315. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10316. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10317. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10318. this._isStencilTestDirty = true;
  10319. this._isStencilMaskDirty = true;
  10320. this._isStencilFuncDirty = true;
  10321. this._isStencilOpDirty = true;
  10322. };
  10323. _StencilState.prototype.apply = function (gl) {
  10324. if (!this.isDirty) {
  10325. return;
  10326. }
  10327. // Stencil test
  10328. if (this._isStencilTestDirty) {
  10329. if (this.stencilTest) {
  10330. gl.enable(gl.STENCIL_TEST);
  10331. }
  10332. else {
  10333. gl.disable(gl.STENCIL_TEST);
  10334. }
  10335. this._isStencilTestDirty = false;
  10336. }
  10337. // Stencil mask
  10338. if (this._isStencilMaskDirty) {
  10339. gl.stencilMask(this.stencilMask);
  10340. this._isStencilMaskDirty = false;
  10341. }
  10342. // Stencil func
  10343. if (this._isStencilFuncDirty) {
  10344. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10345. this._isStencilFuncDirty = false;
  10346. }
  10347. // Stencil op
  10348. if (this._isStencilOpDirty) {
  10349. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10350. this._isStencilOpDirty = false;
  10351. }
  10352. };
  10353. return _StencilState;
  10354. }());
  10355. BABYLON._StencilState = _StencilState;
  10356. })(BABYLON || (BABYLON = {}));
  10357. //# sourceMappingURL=babylon.stencilState.js.map
  10358. "use strict";
  10359. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10360. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10361. s = arguments[i];
  10362. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10363. t[p] = s[p];
  10364. }
  10365. return t;
  10366. };
  10367. var BABYLON;
  10368. (function (BABYLON) {
  10369. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10370. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10371. };
  10372. var compileRawShader = function (gl, source, type) {
  10373. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10374. gl.shaderSource(shader, source);
  10375. gl.compileShader(shader);
  10376. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10377. var log = gl.getShaderInfoLog(shader);
  10378. if (log) {
  10379. throw new Error(log);
  10380. }
  10381. }
  10382. if (!shader) {
  10383. throw new Error("Something went wrong while compile the shader.");
  10384. }
  10385. return shader;
  10386. };
  10387. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10388. var magFilter = gl.NEAREST;
  10389. var minFilter = gl.NEAREST;
  10390. switch (samplingMode) {
  10391. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10392. magFilter = gl.LINEAR;
  10393. if (generateMipMaps) {
  10394. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10395. }
  10396. else {
  10397. minFilter = gl.LINEAR;
  10398. }
  10399. break;
  10400. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10401. magFilter = gl.LINEAR;
  10402. if (generateMipMaps) {
  10403. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10404. }
  10405. else {
  10406. minFilter = gl.LINEAR;
  10407. }
  10408. break;
  10409. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10410. magFilter = gl.NEAREST;
  10411. if (generateMipMaps) {
  10412. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10413. }
  10414. else {
  10415. minFilter = gl.NEAREST;
  10416. }
  10417. break;
  10418. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10419. magFilter = gl.NEAREST;
  10420. if (generateMipMaps) {
  10421. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10422. }
  10423. else {
  10424. minFilter = gl.NEAREST;
  10425. }
  10426. break;
  10427. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10428. magFilter = gl.NEAREST;
  10429. if (generateMipMaps) {
  10430. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10431. }
  10432. else {
  10433. minFilter = gl.LINEAR;
  10434. }
  10435. break;
  10436. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10437. magFilter = gl.NEAREST;
  10438. if (generateMipMaps) {
  10439. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10440. }
  10441. else {
  10442. minFilter = gl.LINEAR;
  10443. }
  10444. break;
  10445. case BABYLON.Texture.NEAREST_LINEAR:
  10446. magFilter = gl.NEAREST;
  10447. minFilter = gl.LINEAR;
  10448. break;
  10449. case BABYLON.Texture.NEAREST_NEAREST:
  10450. magFilter = gl.NEAREST;
  10451. minFilter = gl.NEAREST;
  10452. break;
  10453. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10454. magFilter = gl.LINEAR;
  10455. if (generateMipMaps) {
  10456. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10457. }
  10458. else {
  10459. minFilter = gl.NEAREST;
  10460. }
  10461. break;
  10462. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10463. magFilter = gl.LINEAR;
  10464. if (generateMipMaps) {
  10465. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10466. }
  10467. else {
  10468. minFilter = gl.NEAREST;
  10469. }
  10470. break;
  10471. case BABYLON.Texture.LINEAR_LINEAR:
  10472. magFilter = gl.LINEAR;
  10473. minFilter = gl.LINEAR;
  10474. break;
  10475. case BABYLON.Texture.LINEAR_NEAREST:
  10476. magFilter = gl.LINEAR;
  10477. minFilter = gl.NEAREST;
  10478. break;
  10479. }
  10480. return {
  10481. min: minFilter,
  10482. mag: magFilter
  10483. };
  10484. };
  10485. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10486. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10487. var img;
  10488. var onload = function () {
  10489. loadedImages[index] = img;
  10490. loadedImages._internalCount++;
  10491. if (scene) {
  10492. scene._removePendingData(img);
  10493. }
  10494. if (loadedImages._internalCount === 6) {
  10495. onfinish(loadedImages);
  10496. }
  10497. };
  10498. var onerror = function (message, exception) {
  10499. if (scene) {
  10500. scene._removePendingData(img);
  10501. }
  10502. if (onErrorCallBack) {
  10503. onErrorCallBack(message, exception);
  10504. }
  10505. };
  10506. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10507. if (scene) {
  10508. scene._addPendingData(img);
  10509. }
  10510. };
  10511. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10512. if (onError === void 0) { onError = null; }
  10513. var loadedImages = [];
  10514. loadedImages._internalCount = 0;
  10515. for (var index = 0; index < 6; index++) {
  10516. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10517. }
  10518. };
  10519. var BufferPointer = /** @class */ (function () {
  10520. function BufferPointer() {
  10521. }
  10522. return BufferPointer;
  10523. }());
  10524. var InstancingAttributeInfo = /** @class */ (function () {
  10525. function InstancingAttributeInfo() {
  10526. }
  10527. return InstancingAttributeInfo;
  10528. }());
  10529. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10530. /**
  10531. * Define options used to create a render target texture
  10532. */
  10533. var RenderTargetCreationOptions = /** @class */ (function () {
  10534. function RenderTargetCreationOptions() {
  10535. }
  10536. return RenderTargetCreationOptions;
  10537. }());
  10538. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10539. /**
  10540. * Define options used to create a depth texture
  10541. */
  10542. var DepthTextureCreationOptions = /** @class */ (function () {
  10543. function DepthTextureCreationOptions() {
  10544. }
  10545. return DepthTextureCreationOptions;
  10546. }());
  10547. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10548. /**
  10549. * Regroup several parameters relative to the browser in use
  10550. */
  10551. var EngineCapabilities = /** @class */ (function () {
  10552. function EngineCapabilities() {
  10553. }
  10554. return EngineCapabilities;
  10555. }());
  10556. BABYLON.EngineCapabilities = EngineCapabilities;
  10557. /**
  10558. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10559. */
  10560. var Engine = /** @class */ (function () {
  10561. /**
  10562. * @constructor
  10563. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10564. * @param antialias defines enable antialiasing (default: false)
  10565. * @param options defines further options to be sent to the getContext() function
  10566. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10567. */
  10568. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10569. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10570. var _this = this;
  10571. // Public members
  10572. this.forcePOTTextures = false;
  10573. this.isFullscreen = false;
  10574. this.isPointerLock = false;
  10575. this.cullBackFaces = true;
  10576. this.renderEvenInBackground = true;
  10577. this.preventCacheWipeBetweenFrames = false;
  10578. /**
  10579. * To enable/disable IDB support and avoid XHR on .manifest
  10580. **/
  10581. this.enableOfflineSupport = false;
  10582. this.scenes = new Array();
  10583. this.postProcesses = new Array();
  10584. // Observables
  10585. /**
  10586. * Observable event triggered each time the rendering canvas is resized
  10587. */
  10588. this.onResizeObservable = new BABYLON.Observable();
  10589. /**
  10590. * Observable event triggered each time the canvas loses focus
  10591. */
  10592. this.onCanvasBlurObservable = new BABYLON.Observable();
  10593. /**
  10594. * Observable event triggered each time the canvas gains focus
  10595. */
  10596. this.onCanvasFocusObservable = new BABYLON.Observable();
  10597. /**
  10598. * Observable event triggered each time the canvas receives pointerout event
  10599. */
  10600. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10601. /**
  10602. * Observable event triggered before each texture is initialized
  10603. */
  10604. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10605. //WebVR
  10606. this._vrDisplay = undefined;
  10607. this._vrSupported = false;
  10608. this._vrExclusivePointerMode = false;
  10609. // Uniform buffers list
  10610. this.disableUniformBuffers = false;
  10611. this._uniformBuffers = new Array();
  10612. // Observables
  10613. /**
  10614. * Observable raised when the engine begins a new frame
  10615. */
  10616. this.onBeginFrameObservable = new BABYLON.Observable();
  10617. /**
  10618. * Observable raised when the engine ends the current frame
  10619. */
  10620. this.onEndFrameObservable = new BABYLON.Observable();
  10621. /**
  10622. * Observable raised when the engine is about to compile a shader
  10623. */
  10624. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10625. /**
  10626. * Observable raised when the engine has jsut compiled a shader
  10627. */
  10628. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10629. this._windowIsBackground = false;
  10630. this._webGLVersion = 1.0;
  10631. this._badOS = false;
  10632. this._badDesktopOS = false;
  10633. /**
  10634. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10635. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10636. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10637. */
  10638. this.disableTextureBindingOptimization = false;
  10639. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10640. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10641. this.onVRRequestPresentStart = new BABYLON.Observable();
  10642. this._colorWrite = true;
  10643. this._drawCalls = new BABYLON.PerfCounter();
  10644. this._textureCollisions = new BABYLON.PerfCounter();
  10645. this._renderingQueueLaunched = false;
  10646. this._activeRenderLoops = new Array();
  10647. // Deterministic lockstepMaxSteps
  10648. this._deterministicLockstep = false;
  10649. this._lockstepMaxSteps = 4;
  10650. // Lost context
  10651. this.onContextLostObservable = new BABYLON.Observable();
  10652. this.onContextRestoredObservable = new BABYLON.Observable();
  10653. this._contextWasLost = false;
  10654. this._doNotHandleContextLost = false;
  10655. // FPS
  10656. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10657. this._fps = 60;
  10658. this._deltaTime = 0;
  10659. /**
  10660. * Turn this value on if you want to pause FPS computation when in background
  10661. */
  10662. this.disablePerformanceMonitorInBackground = false;
  10663. // States
  10664. this._depthCullingState = new BABYLON._DepthCullingState();
  10665. this._stencilState = new BABYLON._StencilState();
  10666. this._alphaState = new BABYLON._AlphaState();
  10667. this._alphaMode = Engine.ALPHA_DISABLE;
  10668. // Cache
  10669. this._internalTexturesCache = new Array();
  10670. this._activeChannel = 0;
  10671. this._currentTextureChannel = -1;
  10672. this._boundTexturesCache = {};
  10673. this._compiledEffects = {};
  10674. this._vertexAttribArraysEnabled = [];
  10675. this._uintIndicesCurrentlySet = false;
  10676. this._currentBoundBuffer = new Array();
  10677. this._currentBufferPointers = new Array();
  10678. this._currentInstanceLocations = new Array();
  10679. this._currentInstanceBuffers = new Array();
  10680. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10681. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10682. this._vaoRecordInProgress = false;
  10683. this._mustWipeVertexAttributes = false;
  10684. this._nextFreeTextureSlots = new Array();
  10685. this._maxSimultaneousTextures = 0;
  10686. this._activeRequests = new Array();
  10687. // Hardware supported Compressed Textures
  10688. this._texturesSupported = new Array();
  10689. this._onVRFullScreenTriggered = function () {
  10690. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10691. //get the old size before we change
  10692. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10693. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10694. //get the width and height, change the render size
  10695. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10696. _this.setHardwareScalingLevel(1);
  10697. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10698. }
  10699. else {
  10700. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10701. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10702. }
  10703. };
  10704. this._boundUniforms = {};
  10705. // Register promises
  10706. BABYLON.PromisePolyfill.Apply();
  10707. var canvas = null;
  10708. Engine.Instances.push(this);
  10709. if (!canvasOrContext) {
  10710. return;
  10711. }
  10712. options = options || {};
  10713. if (canvasOrContext.getContext) {
  10714. canvas = canvasOrContext;
  10715. this._renderingCanvas = canvas;
  10716. if (antialias != null) {
  10717. options.antialias = antialias;
  10718. }
  10719. if (options.deterministicLockstep === undefined) {
  10720. options.deterministicLockstep = false;
  10721. }
  10722. if (options.lockstepMaxSteps === undefined) {
  10723. options.lockstepMaxSteps = 4;
  10724. }
  10725. if (options.preserveDrawingBuffer === undefined) {
  10726. options.preserveDrawingBuffer = false;
  10727. }
  10728. if (options.audioEngine === undefined) {
  10729. options.audioEngine = true;
  10730. }
  10731. if (options.stencil === undefined) {
  10732. options.stencil = true;
  10733. }
  10734. this._deterministicLockstep = options.deterministicLockstep;
  10735. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10736. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10737. // Exceptions
  10738. if (navigator && navigator.userAgent) {
  10739. var ua = navigator.userAgent;
  10740. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10741. var exception = _a[_i];
  10742. var key = exception.key;
  10743. var targets = exception.targets;
  10744. if (ua.indexOf(key) > -1) {
  10745. if (exception.capture && exception.captureConstraint) {
  10746. var capture = exception.capture;
  10747. var constraint = exception.captureConstraint;
  10748. var regex = new RegExp(capture);
  10749. var matches = regex.exec(ua);
  10750. if (matches && matches.length > 0) {
  10751. var capturedValue = parseInt(matches[matches.length - 1]);
  10752. if (capturedValue >= constraint) {
  10753. continue;
  10754. }
  10755. }
  10756. }
  10757. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10758. var target = targets_1[_b];
  10759. switch (target) {
  10760. case "uniformBuffer":
  10761. this.disableUniformBuffers = true;
  10762. break;
  10763. case "textureBindingOptimization":
  10764. this.disableTextureBindingOptimization = true;
  10765. break;
  10766. }
  10767. }
  10768. }
  10769. }
  10770. }
  10771. // GL
  10772. if (!options.disableWebGL2Support) {
  10773. try {
  10774. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10775. if (this._gl) {
  10776. this._webGLVersion = 2.0;
  10777. }
  10778. }
  10779. catch (e) {
  10780. // Do nothing
  10781. }
  10782. }
  10783. if (!this._gl) {
  10784. if (!canvas) {
  10785. throw new Error("The provided canvas is null or undefined.");
  10786. }
  10787. try {
  10788. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10789. }
  10790. catch (e) {
  10791. throw new Error("WebGL not supported");
  10792. }
  10793. }
  10794. if (!this._gl) {
  10795. throw new Error("WebGL not supported");
  10796. }
  10797. this._onCanvasFocus = function () {
  10798. _this.onCanvasFocusObservable.notifyObservers(_this);
  10799. };
  10800. this._onCanvasBlur = function () {
  10801. _this.onCanvasBlurObservable.notifyObservers(_this);
  10802. };
  10803. canvas.addEventListener("focus", this._onCanvasFocus);
  10804. canvas.addEventListener("blur", this._onCanvasBlur);
  10805. this._onBlur = function () {
  10806. if (_this.disablePerformanceMonitorInBackground) {
  10807. _this._performanceMonitor.disable();
  10808. }
  10809. _this._windowIsBackground = true;
  10810. };
  10811. this._onFocus = function () {
  10812. if (_this.disablePerformanceMonitorInBackground) {
  10813. _this._performanceMonitor.enable();
  10814. }
  10815. _this._windowIsBackground = false;
  10816. };
  10817. this._onCanvasPointerOut = function (ev) {
  10818. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10819. };
  10820. window.addEventListener("blur", this._onBlur);
  10821. window.addEventListener("focus", this._onFocus);
  10822. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10823. // Context lost
  10824. if (!this._doNotHandleContextLost) {
  10825. this._onContextLost = function (evt) {
  10826. evt.preventDefault();
  10827. _this._contextWasLost = true;
  10828. BABYLON.Tools.Warn("WebGL context lost.");
  10829. _this.onContextLostObservable.notifyObservers(_this);
  10830. };
  10831. this._onContextRestored = function (evt) {
  10832. // Adding a timeout to avoid race condition at browser level
  10833. setTimeout(function () {
  10834. // Rebuild gl context
  10835. _this._initGLContext();
  10836. // Rebuild effects
  10837. _this._rebuildEffects();
  10838. // Rebuild textures
  10839. _this._rebuildInternalTextures();
  10840. // Rebuild buffers
  10841. _this._rebuildBuffers();
  10842. // Cache
  10843. _this.wipeCaches(true);
  10844. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10845. _this.onContextRestoredObservable.notifyObservers(_this);
  10846. _this._contextWasLost = false;
  10847. }, 0);
  10848. };
  10849. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10850. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10851. }
  10852. }
  10853. else {
  10854. this._gl = canvasOrContext;
  10855. this._renderingCanvas = this._gl.canvas;
  10856. if (this._gl.renderbufferStorageMultisample) {
  10857. this._webGLVersion = 2.0;
  10858. }
  10859. options.stencil = this._gl.getContextAttributes().stencil;
  10860. }
  10861. // Viewport
  10862. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10863. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10864. this.resize();
  10865. this._isStencilEnable = options.stencil ? true : false;
  10866. this._initGLContext();
  10867. if (canvas) {
  10868. // Fullscreen
  10869. this._onFullscreenChange = function () {
  10870. if (document.fullscreen !== undefined) {
  10871. _this.isFullscreen = document.fullscreen;
  10872. }
  10873. else if (document.mozFullScreen !== undefined) {
  10874. _this.isFullscreen = document.mozFullScreen;
  10875. }
  10876. else if (document.webkitIsFullScreen !== undefined) {
  10877. _this.isFullscreen = document.webkitIsFullScreen;
  10878. }
  10879. else if (document.msIsFullScreen !== undefined) {
  10880. _this.isFullscreen = document.msIsFullScreen;
  10881. }
  10882. // Pointer lock
  10883. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10884. canvas.requestPointerLock = canvas.requestPointerLock ||
  10885. canvas.msRequestPointerLock ||
  10886. canvas.mozRequestPointerLock ||
  10887. canvas.webkitRequestPointerLock;
  10888. if (canvas.requestPointerLock) {
  10889. canvas.requestPointerLock();
  10890. }
  10891. }
  10892. };
  10893. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10894. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10895. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10896. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10897. // Pointer lock
  10898. this._onPointerLockChange = function () {
  10899. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10900. document.webkitPointerLockElement === canvas ||
  10901. document.msPointerLockElement === canvas ||
  10902. document.pointerLockElement === canvas);
  10903. };
  10904. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10905. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10906. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10907. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10908. this._onVRDisplayPointerRestricted = function () {
  10909. if (canvas) {
  10910. canvas.requestPointerLock();
  10911. }
  10912. };
  10913. this._onVRDisplayPointerUnrestricted = function () {
  10914. document.exitPointerLock();
  10915. };
  10916. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10917. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10918. }
  10919. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10920. Engine.audioEngine = new BABYLON.AudioEngine();
  10921. }
  10922. // Prepare buffer pointers
  10923. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10924. this._currentBufferPointers[i] = new BufferPointer();
  10925. }
  10926. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10927. // Load WebVR Devices
  10928. if (options.autoEnableWebVR) {
  10929. this.initWebVR();
  10930. }
  10931. // Detect if we are running on a faulty buggy OS.
  10932. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10933. // Detect if we are running on a faulty buggy desktop OS.
  10934. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10935. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10936. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10937. }
  10938. Object.defineProperty(Engine, "LastCreatedEngine", {
  10939. get: function () {
  10940. if (Engine.Instances.length === 0) {
  10941. return null;
  10942. }
  10943. return Engine.Instances[Engine.Instances.length - 1];
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "LastCreatedScene", {
  10949. get: function () {
  10950. var lastCreatedEngine = Engine.LastCreatedEngine;
  10951. if (!lastCreatedEngine) {
  10952. return null;
  10953. }
  10954. if (lastCreatedEngine.scenes.length === 0) {
  10955. return null;
  10956. }
  10957. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. /**
  10963. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10964. */
  10965. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10966. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10967. var engine = Engine.Instances[engineIndex];
  10968. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10969. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10970. }
  10971. }
  10972. };
  10973. Object.defineProperty(Engine, "NEVER", {
  10974. get: function () {
  10975. return Engine._NEVER;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Engine, "ALWAYS", {
  10981. get: function () {
  10982. return Engine._ALWAYS;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Engine, "LESS", {
  10988. get: function () {
  10989. return Engine._LESS;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Engine, "EQUAL", {
  10995. get: function () {
  10996. return Engine._EQUAL;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Engine, "LEQUAL", {
  11002. get: function () {
  11003. return Engine._LEQUAL;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Engine, "GREATER", {
  11009. get: function () {
  11010. return Engine._GREATER;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(Engine, "GEQUAL", {
  11016. get: function () {
  11017. return Engine._GEQUAL;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Engine, "NOTEQUAL", {
  11023. get: function () {
  11024. return Engine._NOTEQUAL;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(Engine, "KEEP", {
  11030. get: function () {
  11031. return Engine._KEEP;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(Engine, "REPLACE", {
  11037. get: function () {
  11038. return Engine._REPLACE;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "INCR", {
  11044. get: function () {
  11045. return Engine._INCR;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Engine, "DECR", {
  11051. get: function () {
  11052. return Engine._DECR;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. Object.defineProperty(Engine, "INVERT", {
  11058. get: function () {
  11059. return Engine._INVERT;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "INCR_WRAP", {
  11065. get: function () {
  11066. return Engine._INCR_WRAP;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "DECR_WRAP", {
  11072. get: function () {
  11073. return Engine._DECR_WRAP;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11079. get: function () {
  11080. return Engine._ALPHA_DISABLE;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11086. get: function () {
  11087. return Engine._ALPHA_ONEONE;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "ALPHA_ADD", {
  11093. get: function () {
  11094. return Engine._ALPHA_ADD;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11100. get: function () {
  11101. return Engine._ALPHA_COMBINE;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11107. get: function () {
  11108. return Engine._ALPHA_SUBTRACT;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11114. get: function () {
  11115. return Engine._ALPHA_MULTIPLY;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11121. get: function () {
  11122. return Engine._ALPHA_MAXIMIZED;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11128. get: function () {
  11129. return Engine._ALPHA_PREMULTIPLIED;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11135. get: function () {
  11136. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11142. get: function () {
  11143. return Engine._ALPHA_INTERPOLATE;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11149. get: function () {
  11150. return Engine._ALPHA_SCREENMODE;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11156. get: function () {
  11157. return Engine._DELAYLOADSTATE_NONE;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11163. get: function () {
  11164. return Engine._DELAYLOADSTATE_LOADED;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11170. get: function () {
  11171. return Engine._DELAYLOADSTATE_LOADING;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11177. get: function () {
  11178. return Engine._DELAYLOADSTATE_NOTLOADED;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11184. get: function () {
  11185. return Engine._TEXTUREFORMAT_ALPHA;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11191. get: function () {
  11192. return Engine._TEXTUREFORMAT_LUMINANCE;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11198. /**
  11199. * R32F
  11200. */
  11201. get: function () {
  11202. return Engine._TEXTUREFORMAT_R32F;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11208. /**
  11209. * RG32F
  11210. */
  11211. get: function () {
  11212. return Engine._TEXTUREFORMAT_RG32F;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11218. /**
  11219. * RGB32F
  11220. */
  11221. get: function () {
  11222. return Engine._TEXTUREFORMAT_RGB32F;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11228. /**
  11229. * RGBA32F
  11230. */
  11231. get: function () {
  11232. return Engine._TEXTUREFORMAT_RGBA32F;
  11233. },
  11234. enumerable: true,
  11235. configurable: true
  11236. });
  11237. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11238. get: function () {
  11239. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11245. get: function () {
  11246. return Engine._TEXTUREFORMAT_RGB;
  11247. },
  11248. enumerable: true,
  11249. configurable: true
  11250. });
  11251. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11252. get: function () {
  11253. return Engine._TEXTUREFORMAT_RGBA;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11259. get: function () {
  11260. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11266. get: function () {
  11267. return Engine._TEXTURETYPE_FLOAT;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11273. get: function () {
  11274. return Engine._TEXTURETYPE_HALF_FLOAT;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11280. get: function () {
  11281. return Engine._SCALEMODE_FLOOR;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11287. get: function () {
  11288. return Engine._SCALEMODE_NEAREST;
  11289. },
  11290. enumerable: true,
  11291. configurable: true
  11292. });
  11293. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11294. get: function () {
  11295. return Engine._SCALEMODE_CEILING;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine, "Version", {
  11301. get: function () {
  11302. return "3.2.0-beta.2";
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11308. get: function () {
  11309. return this._vrExclusivePointerMode;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11315. get: function () {
  11316. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11322. get: function () {
  11323. return this._webGLVersion < 2 || this.forcePOTTextures;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(Engine.prototype, "badOS", {
  11329. get: function () {
  11330. return this._badOS;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11336. get: function () {
  11337. return this._badDesktopOS;
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11343. get: function () {
  11344. return this._performanceMonitor;
  11345. },
  11346. enumerable: true,
  11347. configurable: true
  11348. });
  11349. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11350. get: function () {
  11351. return this._texturesSupported;
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11357. get: function () {
  11358. return this._textureFormatInUse;
  11359. },
  11360. enumerable: true,
  11361. configurable: true
  11362. });
  11363. Object.defineProperty(Engine.prototype, "currentViewport", {
  11364. get: function () {
  11365. return this._cachedViewport;
  11366. },
  11367. enumerable: true,
  11368. configurable: true
  11369. });
  11370. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11371. // Empty texture
  11372. get: function () {
  11373. if (!this._emptyTexture) {
  11374. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11375. }
  11376. return this._emptyTexture;
  11377. },
  11378. enumerable: true,
  11379. configurable: true
  11380. });
  11381. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11382. get: function () {
  11383. if (!this._emptyTexture3D) {
  11384. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11385. }
  11386. return this._emptyTexture3D;
  11387. },
  11388. enumerable: true,
  11389. configurable: true
  11390. });
  11391. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11392. get: function () {
  11393. if (!this._emptyCubeTexture) {
  11394. var faceData = new Uint8Array(4);
  11395. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11396. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11397. }
  11398. return this._emptyCubeTexture;
  11399. },
  11400. enumerable: true,
  11401. configurable: true
  11402. });
  11403. Engine.prototype._rebuildInternalTextures = function () {
  11404. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11405. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11406. var internalTexture = currentState_1[_i];
  11407. internalTexture._rebuild();
  11408. }
  11409. };
  11410. Engine.prototype._rebuildEffects = function () {
  11411. for (var key in this._compiledEffects) {
  11412. var effect = this._compiledEffects[key];
  11413. effect._prepareEffect();
  11414. }
  11415. BABYLON.Effect.ResetCache();
  11416. };
  11417. Engine.prototype._rebuildBuffers = function () {
  11418. // Index / Vertex
  11419. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11420. var scene = _a[_i];
  11421. scene.resetCachedMaterial();
  11422. scene._rebuildGeometries();
  11423. scene._rebuildTextures();
  11424. }
  11425. // Uniforms
  11426. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11427. var uniformBuffer = _c[_b];
  11428. uniformBuffer._rebuild();
  11429. }
  11430. };
  11431. Engine.prototype._initGLContext = function () {
  11432. // Caps
  11433. this._caps = new EngineCapabilities();
  11434. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11435. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11436. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11437. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11438. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11439. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11440. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11441. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11442. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11443. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11444. // Infos
  11445. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11446. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11447. if (rendererInfo != null) {
  11448. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11449. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11450. }
  11451. if (!this._glVendor) {
  11452. this._glVendor = "Unknown vendor";
  11453. }
  11454. if (!this._glRenderer) {
  11455. this._glRenderer = "Unknown renderer";
  11456. }
  11457. // Constants
  11458. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11459. if (this._gl.RGBA16F !== 0x881A) {
  11460. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11461. }
  11462. if (this._gl.RGBA32F !== 0x8814) {
  11463. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11464. }
  11465. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11466. this._gl.DEPTH24_STENCIL8 = 35056;
  11467. }
  11468. // Extensions
  11469. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11470. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11471. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11472. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11473. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11474. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11475. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11476. 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');
  11477. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11478. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11479. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11480. this._caps.highPrecisionShaderSupported = true;
  11481. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11482. if (this._caps.timerQuery) {
  11483. if (this._webGLVersion === 1) {
  11484. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11485. }
  11486. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11487. }
  11488. // Checks if some of the format renders first to allow the use of webgl inspector.
  11489. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11490. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11491. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11492. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11493. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11494. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11495. if (this._webGLVersion > 1) {
  11496. this._gl.HALF_FLOAT_OES = 0x140B;
  11497. }
  11498. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11499. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11500. // Draw buffers
  11501. if (this._webGLVersion > 1) {
  11502. this._caps.drawBuffersExtension = true;
  11503. }
  11504. else {
  11505. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11506. if (drawBuffersExtension !== null) {
  11507. this._caps.drawBuffersExtension = true;
  11508. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11509. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11510. for (var i = 0; i < 16; i++) {
  11511. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11512. }
  11513. }
  11514. else {
  11515. this._caps.drawBuffersExtension = false;
  11516. }
  11517. }
  11518. // Depth Texture
  11519. if (this._webGLVersion > 1) {
  11520. this._caps.depthTextureExtension = true;
  11521. }
  11522. else {
  11523. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11524. if (depthTextureExtension != null) {
  11525. this._caps.depthTextureExtension = true;
  11526. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11527. }
  11528. }
  11529. // Vertex array object
  11530. if (this._webGLVersion > 1) {
  11531. this._caps.vertexArrayObject = true;
  11532. }
  11533. else {
  11534. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11535. if (vertexArrayObjectExtension != null) {
  11536. this._caps.vertexArrayObject = true;
  11537. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11538. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11539. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11540. }
  11541. else {
  11542. this._caps.vertexArrayObject = false;
  11543. }
  11544. }
  11545. // Instances count
  11546. if (this._webGLVersion > 1) {
  11547. this._caps.instancedArrays = true;
  11548. }
  11549. else {
  11550. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11551. if (instanceExtension != null) {
  11552. this._caps.instancedArrays = true;
  11553. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11554. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11555. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11556. }
  11557. else {
  11558. this._caps.instancedArrays = false;
  11559. }
  11560. }
  11561. // Intelligently add supported compressed formats in order to check for.
  11562. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11563. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11564. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11565. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11566. if (this._caps.astc)
  11567. this.texturesSupported.push('-astc.ktx');
  11568. if (this._caps.s3tc)
  11569. this.texturesSupported.push('-dxt.ktx');
  11570. if (this._caps.pvrtc)
  11571. this.texturesSupported.push('-pvrtc.ktx');
  11572. if (this._caps.etc2)
  11573. this.texturesSupported.push('-etc2.ktx');
  11574. if (this._caps.etc1)
  11575. this.texturesSupported.push('-etc1.ktx');
  11576. if (this._gl.getShaderPrecisionFormat) {
  11577. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11578. if (highp) {
  11579. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11580. }
  11581. }
  11582. // Depth buffer
  11583. this.setDepthBuffer(true);
  11584. this.setDepthFunctionToLessOrEqual();
  11585. this.setDepthWrite(true);
  11586. // Texture maps
  11587. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11588. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11589. this._nextFreeTextureSlots.push(slot);
  11590. }
  11591. };
  11592. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11593. get: function () {
  11594. return this._webGLVersion;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11600. /**
  11601. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11602. */
  11603. get: function () {
  11604. return this._isStencilEnable;
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. Engine.prototype._prepareWorkingCanvas = function () {
  11610. if (this._workingCanvas) {
  11611. return;
  11612. }
  11613. this._workingCanvas = document.createElement("canvas");
  11614. var context = this._workingCanvas.getContext("2d");
  11615. if (context) {
  11616. this._workingContext = context;
  11617. }
  11618. };
  11619. Engine.prototype.resetTextureCache = function () {
  11620. for (var key in this._boundTexturesCache) {
  11621. var boundTexture = this._boundTexturesCache[key];
  11622. if (boundTexture) {
  11623. this._removeDesignatedSlot(boundTexture);
  11624. }
  11625. this._boundTexturesCache[key] = null;
  11626. }
  11627. if (!this.disableTextureBindingOptimization) {
  11628. this._nextFreeTextureSlots = [];
  11629. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11630. this._nextFreeTextureSlots.push(slot);
  11631. }
  11632. }
  11633. this._currentTextureChannel = -1;
  11634. };
  11635. Engine.prototype.isDeterministicLockStep = function () {
  11636. return this._deterministicLockstep;
  11637. };
  11638. Engine.prototype.getLockstepMaxSteps = function () {
  11639. return this._lockstepMaxSteps;
  11640. };
  11641. Engine.prototype.getGlInfo = function () {
  11642. return {
  11643. vendor: this._glVendor,
  11644. renderer: this._glRenderer,
  11645. version: this._glVersion
  11646. };
  11647. };
  11648. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11649. if (useScreen === void 0) { useScreen = false; }
  11650. var viewport = camera.viewport;
  11651. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11652. };
  11653. Engine.prototype.getRenderWidth = function (useScreen) {
  11654. if (useScreen === void 0) { useScreen = false; }
  11655. if (!useScreen && this._currentRenderTarget) {
  11656. return this._currentRenderTarget.width;
  11657. }
  11658. return this._gl.drawingBufferWidth;
  11659. };
  11660. Engine.prototype.getRenderHeight = function (useScreen) {
  11661. if (useScreen === void 0) { useScreen = false; }
  11662. if (!useScreen && this._currentRenderTarget) {
  11663. return this._currentRenderTarget.height;
  11664. }
  11665. return this._gl.drawingBufferHeight;
  11666. };
  11667. Engine.prototype.getRenderingCanvas = function () {
  11668. return this._renderingCanvas;
  11669. };
  11670. Engine.prototype.getRenderingCanvasClientRect = function () {
  11671. if (!this._renderingCanvas) {
  11672. return null;
  11673. }
  11674. return this._renderingCanvas.getBoundingClientRect();
  11675. };
  11676. Engine.prototype.setHardwareScalingLevel = function (level) {
  11677. this._hardwareScalingLevel = level;
  11678. this.resize();
  11679. };
  11680. Engine.prototype.getHardwareScalingLevel = function () {
  11681. return this._hardwareScalingLevel;
  11682. };
  11683. Engine.prototype.getLoadedTexturesCache = function () {
  11684. return this._internalTexturesCache;
  11685. };
  11686. Engine.prototype.getCaps = function () {
  11687. return this._caps;
  11688. };
  11689. Object.defineProperty(Engine.prototype, "drawCalls", {
  11690. /** The number of draw calls submitted last frame */
  11691. get: function () {
  11692. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11693. return 0;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11699. get: function () {
  11700. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11701. return null;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Engine.prototype.getDepthFunction = function () {
  11707. return this._depthCullingState.depthFunc;
  11708. };
  11709. Engine.prototype.setDepthFunction = function (depthFunc) {
  11710. this._depthCullingState.depthFunc = depthFunc;
  11711. };
  11712. Engine.prototype.setDepthFunctionToGreater = function () {
  11713. this._depthCullingState.depthFunc = this._gl.GREATER;
  11714. };
  11715. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11716. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11717. };
  11718. Engine.prototype.setDepthFunctionToLess = function () {
  11719. this._depthCullingState.depthFunc = this._gl.LESS;
  11720. };
  11721. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11722. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11723. };
  11724. Engine.prototype.getStencilBuffer = function () {
  11725. return this._stencilState.stencilTest;
  11726. };
  11727. Engine.prototype.setStencilBuffer = function (enable) {
  11728. this._stencilState.stencilTest = enable;
  11729. };
  11730. Engine.prototype.getStencilMask = function () {
  11731. return this._stencilState.stencilMask;
  11732. };
  11733. Engine.prototype.setStencilMask = function (mask) {
  11734. this._stencilState.stencilMask = mask;
  11735. };
  11736. Engine.prototype.getStencilFunction = function () {
  11737. return this._stencilState.stencilFunc;
  11738. };
  11739. Engine.prototype.getStencilFunctionReference = function () {
  11740. return this._stencilState.stencilFuncRef;
  11741. };
  11742. Engine.prototype.getStencilFunctionMask = function () {
  11743. return this._stencilState.stencilFuncMask;
  11744. };
  11745. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11746. this._stencilState.stencilFunc = stencilFunc;
  11747. };
  11748. Engine.prototype.setStencilFunctionReference = function (reference) {
  11749. this._stencilState.stencilFuncRef = reference;
  11750. };
  11751. Engine.prototype.setStencilFunctionMask = function (mask) {
  11752. this._stencilState.stencilFuncMask = mask;
  11753. };
  11754. Engine.prototype.getStencilOperationFail = function () {
  11755. return this._stencilState.stencilOpStencilFail;
  11756. };
  11757. Engine.prototype.getStencilOperationDepthFail = function () {
  11758. return this._stencilState.stencilOpDepthFail;
  11759. };
  11760. Engine.prototype.getStencilOperationPass = function () {
  11761. return this._stencilState.stencilOpStencilDepthPass;
  11762. };
  11763. Engine.prototype.setStencilOperationFail = function (operation) {
  11764. this._stencilState.stencilOpStencilFail = operation;
  11765. };
  11766. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11767. this._stencilState.stencilOpDepthFail = operation;
  11768. };
  11769. Engine.prototype.setStencilOperationPass = function (operation) {
  11770. this._stencilState.stencilOpStencilDepthPass = operation;
  11771. };
  11772. Engine.prototype.setDitheringState = function (value) {
  11773. if (value) {
  11774. this._gl.enable(this._gl.DITHER);
  11775. }
  11776. else {
  11777. this._gl.disable(this._gl.DITHER);
  11778. }
  11779. };
  11780. Engine.prototype.setRasterizerState = function (value) {
  11781. if (value) {
  11782. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11783. }
  11784. else {
  11785. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11786. }
  11787. };
  11788. /**
  11789. * stop executing a render loop function and remove it from the execution array
  11790. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11791. */
  11792. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11793. if (!renderFunction) {
  11794. this._activeRenderLoops = [];
  11795. return;
  11796. }
  11797. var index = this._activeRenderLoops.indexOf(renderFunction);
  11798. if (index >= 0) {
  11799. this._activeRenderLoops.splice(index, 1);
  11800. }
  11801. };
  11802. Engine.prototype._renderLoop = function () {
  11803. if (!this._contextWasLost) {
  11804. var shouldRender = true;
  11805. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11806. shouldRender = false;
  11807. }
  11808. if (shouldRender) {
  11809. // Start new frame
  11810. this.beginFrame();
  11811. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11812. var renderFunction = this._activeRenderLoops[index];
  11813. renderFunction();
  11814. }
  11815. // Present
  11816. this.endFrame();
  11817. }
  11818. }
  11819. if (this._activeRenderLoops.length > 0) {
  11820. // Register new frame
  11821. var requester = null;
  11822. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11823. requester = this._vrDisplay;
  11824. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11825. }
  11826. else {
  11827. this._renderingQueueLaunched = false;
  11828. }
  11829. };
  11830. /**
  11831. * Register and execute a render loop. The engine can have more than one render function.
  11832. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11833. * @example
  11834. * engine.runRenderLoop(function () {
  11835. * scene.render()
  11836. * })
  11837. */
  11838. Engine.prototype.runRenderLoop = function (renderFunction) {
  11839. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11840. return;
  11841. }
  11842. this._activeRenderLoops.push(renderFunction);
  11843. if (!this._renderingQueueLaunched) {
  11844. this._renderingQueueLaunched = true;
  11845. this._bindedRenderFunction = this._renderLoop.bind(this);
  11846. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11847. }
  11848. };
  11849. /**
  11850. * Toggle full screen mode.
  11851. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11852. * @param {any} options - an options object to be sent to the requestFullscreen function
  11853. */
  11854. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11855. if (this.isFullscreen) {
  11856. BABYLON.Tools.ExitFullscreen();
  11857. }
  11858. else {
  11859. this._pointerLockRequested = requestPointerLock;
  11860. if (this._renderingCanvas) {
  11861. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11862. }
  11863. }
  11864. };
  11865. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11866. if (stencil === void 0) { stencil = false; }
  11867. this.applyStates();
  11868. var mode = 0;
  11869. if (backBuffer && color) {
  11870. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11871. mode |= this._gl.COLOR_BUFFER_BIT;
  11872. }
  11873. if (depth) {
  11874. this._gl.clearDepth(1.0);
  11875. mode |= this._gl.DEPTH_BUFFER_BIT;
  11876. }
  11877. if (stencil) {
  11878. this._gl.clearStencil(0);
  11879. mode |= this._gl.STENCIL_BUFFER_BIT;
  11880. }
  11881. this._gl.clear(mode);
  11882. };
  11883. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11884. var gl = this._gl;
  11885. // Save state
  11886. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11887. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11888. // Change state
  11889. gl.enable(gl.SCISSOR_TEST);
  11890. gl.scissor(x, y, width, height);
  11891. // Clear
  11892. this.clear(clearColor, true, true, true);
  11893. // Restore state
  11894. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11895. if (curScissor === true) {
  11896. gl.enable(gl.SCISSOR_TEST);
  11897. }
  11898. else {
  11899. gl.disable(gl.SCISSOR_TEST);
  11900. }
  11901. };
  11902. /**
  11903. * Set the WebGL's viewport
  11904. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11905. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11906. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11907. */
  11908. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11909. var width = requiredWidth || this.getRenderWidth();
  11910. var height = requiredHeight || this.getRenderHeight();
  11911. var x = viewport.x || 0;
  11912. var y = viewport.y || 0;
  11913. this._cachedViewport = viewport;
  11914. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11915. };
  11916. /**
  11917. * Directly set the WebGL Viewport
  11918. * The x, y, width & height are directly passed to the WebGL call
  11919. * @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.
  11920. */
  11921. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11922. var currentViewport = this._cachedViewport;
  11923. this._cachedViewport = null;
  11924. this._gl.viewport(x, y, width, height);
  11925. return currentViewport;
  11926. };
  11927. Engine.prototype.beginFrame = function () {
  11928. this.onBeginFrameObservable.notifyObservers(this);
  11929. this._measureFps();
  11930. };
  11931. Engine.prototype.endFrame = function () {
  11932. //force a flush in case we are using a bad OS.
  11933. if (this._badOS) {
  11934. this.flushFramebuffer();
  11935. }
  11936. //submit frame to the vr device, if enabled
  11937. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11938. // TODO: We should only submit the frame if we read frameData successfully.
  11939. this._vrDisplay.submitFrame();
  11940. }
  11941. this.onEndFrameObservable.notifyObservers(this);
  11942. };
  11943. /**
  11944. * resize the view according to the canvas' size.
  11945. * @example
  11946. * window.addEventListener("resize", function () {
  11947. * engine.resize();
  11948. * });
  11949. */
  11950. Engine.prototype.resize = function () {
  11951. // We're not resizing the size of the canvas while in VR mode & presenting
  11952. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11953. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11954. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11955. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11956. }
  11957. };
  11958. /**
  11959. * force a specific size of the canvas
  11960. * @param {number} width - the new canvas' width
  11961. * @param {number} height - the new canvas' height
  11962. */
  11963. Engine.prototype.setSize = function (width, height) {
  11964. if (!this._renderingCanvas) {
  11965. return;
  11966. }
  11967. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11968. return;
  11969. }
  11970. this._renderingCanvas.width = width;
  11971. this._renderingCanvas.height = height;
  11972. for (var index = 0; index < this.scenes.length; index++) {
  11973. var scene = this.scenes[index];
  11974. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11975. var cam = scene.cameras[camIndex];
  11976. cam._currentRenderId = 0;
  11977. }
  11978. }
  11979. if (this.onResizeObservable.hasObservers) {
  11980. this.onResizeObservable.notifyObservers(this);
  11981. }
  11982. };
  11983. // WebVR functions
  11984. Engine.prototype.isVRDevicePresent = function () {
  11985. return !!this._vrDisplay;
  11986. };
  11987. Engine.prototype.getVRDevice = function () {
  11988. return this._vrDisplay;
  11989. };
  11990. /**
  11991. * Initializes a webVR display and starts listening to display change events.
  11992. * The onVRDisplayChangedObservable will be notified upon these changes.
  11993. * @returns The onVRDisplayChangedObservable.
  11994. */
  11995. Engine.prototype.initWebVR = function () {
  11996. this.initWebVRAsync();
  11997. return this.onVRDisplayChangedObservable;
  11998. };
  11999. /**
  12000. * Initializes a webVR display and starts listening to display change events.
  12001. * The onVRDisplayChangedObservable will be notified upon these changes.
  12002. * @returns A promise containing a VRDisplay and if vr is supported.
  12003. */
  12004. Engine.prototype.initWebVRAsync = function () {
  12005. var _this = this;
  12006. var notifyObservers = function () {
  12007. var eventArgs = {
  12008. vrDisplay: _this._vrDisplay,
  12009. vrSupported: _this._vrSupported
  12010. };
  12011. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12012. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12013. };
  12014. if (!this._onVrDisplayConnect) {
  12015. this._onVrDisplayConnect = function (event) {
  12016. _this._vrDisplay = event.display;
  12017. notifyObservers();
  12018. };
  12019. this._onVrDisplayDisconnect = function () {
  12020. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12021. _this._vrDisplay = undefined;
  12022. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12023. notifyObservers();
  12024. };
  12025. this._onVrDisplayPresentChange = function () {
  12026. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12027. };
  12028. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12029. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12030. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12031. }
  12032. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12033. this._webVRInitPromise.then(notifyObservers);
  12034. return this._webVRInitPromise;
  12035. };
  12036. Engine.prototype.enableVR = function () {
  12037. var _this = this;
  12038. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12039. var onResolved = function () {
  12040. _this.onVRRequestPresentComplete.notifyObservers(true);
  12041. _this._onVRFullScreenTriggered();
  12042. };
  12043. var onRejected = function () {
  12044. _this.onVRRequestPresentComplete.notifyObservers(false);
  12045. };
  12046. this.onVRRequestPresentStart.notifyObservers(this);
  12047. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12048. }
  12049. };
  12050. Engine.prototype.disableVR = function () {
  12051. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12052. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12053. }
  12054. };
  12055. Engine.prototype._getVRDisplaysAsync = function () {
  12056. var _this = this;
  12057. return new Promise(function (res, rej) {
  12058. if (navigator.getVRDisplays) {
  12059. navigator.getVRDisplays().then(function (devices) {
  12060. _this._vrSupported = true;
  12061. // note that devices may actually be an empty array. This is fine;
  12062. // we expect this._vrDisplay to be undefined in this case.
  12063. _this._vrDisplay = devices[0];
  12064. res({
  12065. vrDisplay: _this._vrDisplay,
  12066. vrSupported: _this._vrSupported
  12067. });
  12068. });
  12069. }
  12070. else {
  12071. _this._vrDisplay = undefined;
  12072. _this._vrSupported = false;
  12073. res({
  12074. vrDisplay: _this._vrDisplay,
  12075. vrSupported: _this._vrSupported
  12076. });
  12077. }
  12078. });
  12079. };
  12080. /**
  12081. * Binds the frame buffer to the specified texture.
  12082. * @param texture The texture to render to or null for the default canvas
  12083. * @param faceIndex The face of the texture to render to in case of cube texture
  12084. * @param requiredWidth The width of the target to render to
  12085. * @param requiredHeight The height of the target to render to
  12086. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12087. * @param depthStencilTexture The depth stencil texture to use to render
  12088. */
  12089. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12090. if (this._currentRenderTarget) {
  12091. this.unBindFramebuffer(this._currentRenderTarget);
  12092. }
  12093. this._currentRenderTarget = texture;
  12094. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12095. var gl = this._gl;
  12096. if (texture.isCube) {
  12097. if (faceIndex === undefined) {
  12098. faceIndex = 0;
  12099. }
  12100. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12101. if (depthStencilTexture) {
  12102. if (depthStencilTexture._generateStencilBuffer) {
  12103. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12104. }
  12105. else {
  12106. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12107. }
  12108. }
  12109. }
  12110. if (this._cachedViewport && !forceFullscreenViewport) {
  12111. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12112. }
  12113. else {
  12114. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12115. }
  12116. this.wipeCaches();
  12117. };
  12118. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12119. if (this._currentFramebuffer !== framebuffer) {
  12120. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12121. this._currentFramebuffer = framebuffer;
  12122. }
  12123. };
  12124. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12125. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12126. this._currentRenderTarget = null;
  12127. // If MSAA, we need to bitblt back to main texture
  12128. var gl = this._gl;
  12129. if (texture._MSAAFramebuffer) {
  12130. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12131. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12132. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12133. }
  12134. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12135. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12136. gl.generateMipmap(gl.TEXTURE_2D);
  12137. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12138. }
  12139. if (onBeforeUnbind) {
  12140. if (texture._MSAAFramebuffer) {
  12141. // Bind the correct framebuffer
  12142. this.bindUnboundFramebuffer(texture._framebuffer);
  12143. }
  12144. onBeforeUnbind();
  12145. }
  12146. this.bindUnboundFramebuffer(null);
  12147. };
  12148. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12149. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12150. this._currentRenderTarget = null;
  12151. // If MSAA, we need to bitblt back to main texture
  12152. var gl = this._gl;
  12153. if (textures[0]._MSAAFramebuffer) {
  12154. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12155. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12156. var attachments = textures[0]._attachments;
  12157. if (!attachments) {
  12158. attachments = new Array(textures.length);
  12159. textures[0]._attachments = attachments;
  12160. }
  12161. for (var i = 0; i < textures.length; i++) {
  12162. var texture = textures[i];
  12163. for (var j = 0; j < attachments.length; j++) {
  12164. attachments[j] = gl.NONE;
  12165. }
  12166. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12167. gl.readBuffer(attachments[i]);
  12168. gl.drawBuffers(attachments);
  12169. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12170. }
  12171. for (var i = 0; i < attachments.length; i++) {
  12172. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12173. }
  12174. gl.drawBuffers(attachments);
  12175. }
  12176. for (var i = 0; i < textures.length; i++) {
  12177. var texture = textures[i];
  12178. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12179. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12180. gl.generateMipmap(gl.TEXTURE_2D);
  12181. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12182. }
  12183. }
  12184. if (onBeforeUnbind) {
  12185. if (textures[0]._MSAAFramebuffer) {
  12186. // Bind the correct framebuffer
  12187. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12188. }
  12189. onBeforeUnbind();
  12190. }
  12191. this.bindUnboundFramebuffer(null);
  12192. };
  12193. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12194. if (texture.generateMipMaps) {
  12195. var gl = this._gl;
  12196. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12197. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12198. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12199. }
  12200. };
  12201. Engine.prototype.flushFramebuffer = function () {
  12202. this._gl.flush();
  12203. };
  12204. Engine.prototype.restoreDefaultFramebuffer = function () {
  12205. if (this._currentRenderTarget) {
  12206. this.unBindFramebuffer(this._currentRenderTarget);
  12207. }
  12208. else {
  12209. this.bindUnboundFramebuffer(null);
  12210. }
  12211. if (this._cachedViewport) {
  12212. this.setViewport(this._cachedViewport);
  12213. }
  12214. this.wipeCaches();
  12215. };
  12216. // UBOs
  12217. Engine.prototype.createUniformBuffer = function (elements) {
  12218. var ubo = this._gl.createBuffer();
  12219. if (!ubo) {
  12220. throw new Error("Unable to create uniform buffer");
  12221. }
  12222. this.bindUniformBuffer(ubo);
  12223. if (elements instanceof Float32Array) {
  12224. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12225. }
  12226. else {
  12227. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12228. }
  12229. this.bindUniformBuffer(null);
  12230. ubo.references = 1;
  12231. return ubo;
  12232. };
  12233. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12234. var ubo = this._gl.createBuffer();
  12235. if (!ubo) {
  12236. throw new Error("Unable to create dynamic uniform buffer");
  12237. }
  12238. this.bindUniformBuffer(ubo);
  12239. if (elements instanceof Float32Array) {
  12240. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12241. }
  12242. else {
  12243. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12244. }
  12245. this.bindUniformBuffer(null);
  12246. ubo.references = 1;
  12247. return ubo;
  12248. };
  12249. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12250. this.bindUniformBuffer(uniformBuffer);
  12251. if (offset === undefined) {
  12252. offset = 0;
  12253. }
  12254. if (count === undefined) {
  12255. if (elements instanceof Float32Array) {
  12256. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12257. }
  12258. else {
  12259. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12260. }
  12261. }
  12262. else {
  12263. if (elements instanceof Float32Array) {
  12264. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12265. }
  12266. else {
  12267. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12268. }
  12269. }
  12270. this.bindUniformBuffer(null);
  12271. };
  12272. // VBOs
  12273. Engine.prototype._resetVertexBufferBinding = function () {
  12274. this.bindArrayBuffer(null);
  12275. this._cachedVertexBuffers = null;
  12276. };
  12277. Engine.prototype.createVertexBuffer = function (vertices) {
  12278. var vbo = this._gl.createBuffer();
  12279. if (!vbo) {
  12280. throw new Error("Unable to create vertex buffer");
  12281. }
  12282. this.bindArrayBuffer(vbo);
  12283. if (vertices instanceof Float32Array) {
  12284. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12285. }
  12286. else {
  12287. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12288. }
  12289. this._resetVertexBufferBinding();
  12290. vbo.references = 1;
  12291. return vbo;
  12292. };
  12293. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12294. var vbo = this._gl.createBuffer();
  12295. if (!vbo) {
  12296. throw new Error("Unable to create dynamic vertex buffer");
  12297. }
  12298. this.bindArrayBuffer(vbo);
  12299. if (vertices instanceof Float32Array) {
  12300. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12301. }
  12302. else {
  12303. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12304. }
  12305. this._resetVertexBufferBinding();
  12306. vbo.references = 1;
  12307. return vbo;
  12308. };
  12309. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12310. if (offset === void 0) { offset = 0; }
  12311. // Force cache update
  12312. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12313. this.bindIndexBuffer(indexBuffer);
  12314. var arrayBuffer;
  12315. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12316. arrayBuffer = indices;
  12317. }
  12318. else {
  12319. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12320. }
  12321. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12322. this._resetIndexBufferBinding();
  12323. };
  12324. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12325. this.bindArrayBuffer(vertexBuffer);
  12326. if (offset === undefined) {
  12327. offset = 0;
  12328. }
  12329. if (count === undefined) {
  12330. if (vertices instanceof Float32Array) {
  12331. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12332. }
  12333. else {
  12334. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12335. }
  12336. }
  12337. else {
  12338. if (vertices instanceof Float32Array) {
  12339. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12340. }
  12341. else {
  12342. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12343. }
  12344. }
  12345. this._resetVertexBufferBinding();
  12346. };
  12347. Engine.prototype._resetIndexBufferBinding = function () {
  12348. this.bindIndexBuffer(null);
  12349. this._cachedIndexBuffer = null;
  12350. };
  12351. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12352. var vbo = this._gl.createBuffer();
  12353. if (!vbo) {
  12354. throw new Error("Unable to create index buffer");
  12355. }
  12356. this.bindIndexBuffer(vbo);
  12357. // Check for 32 bits indices
  12358. var arrayBuffer;
  12359. var need32Bits = false;
  12360. if (indices instanceof Uint16Array) {
  12361. arrayBuffer = indices;
  12362. }
  12363. else {
  12364. //check 32 bit support
  12365. if (this._caps.uintIndices) {
  12366. if (indices instanceof Uint32Array) {
  12367. arrayBuffer = indices;
  12368. need32Bits = true;
  12369. }
  12370. else {
  12371. //number[] or Int32Array, check if 32 bit is necessary
  12372. for (var index = 0; index < indices.length; index++) {
  12373. if (indices[index] > 65535) {
  12374. need32Bits = true;
  12375. break;
  12376. }
  12377. }
  12378. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12379. }
  12380. }
  12381. else {
  12382. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12383. arrayBuffer = new Uint16Array(indices);
  12384. }
  12385. }
  12386. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12387. this._resetIndexBufferBinding();
  12388. vbo.references = 1;
  12389. vbo.is32Bits = need32Bits;
  12390. return vbo;
  12391. };
  12392. Engine.prototype.bindArrayBuffer = function (buffer) {
  12393. if (!this._vaoRecordInProgress) {
  12394. this._unbindVertexArrayObject();
  12395. }
  12396. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12397. };
  12398. Engine.prototype.bindUniformBuffer = function (buffer) {
  12399. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12400. };
  12401. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12402. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12403. };
  12404. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12405. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12406. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12407. };
  12408. ;
  12409. Engine.prototype.bindIndexBuffer = function (buffer) {
  12410. if (!this._vaoRecordInProgress) {
  12411. this._unbindVertexArrayObject();
  12412. }
  12413. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12414. };
  12415. Engine.prototype.bindBuffer = function (buffer, target) {
  12416. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12417. this._gl.bindBuffer(target, buffer);
  12418. this._currentBoundBuffer[target] = buffer;
  12419. }
  12420. };
  12421. Engine.prototype.updateArrayBuffer = function (data) {
  12422. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12423. };
  12424. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12425. var pointer = this._currentBufferPointers[indx];
  12426. var changed = false;
  12427. if (!pointer.active) {
  12428. changed = true;
  12429. pointer.active = true;
  12430. pointer.index = indx;
  12431. pointer.size = size;
  12432. pointer.type = type;
  12433. pointer.normalized = normalized;
  12434. pointer.stride = stride;
  12435. pointer.offset = offset;
  12436. pointer.buffer = buffer;
  12437. }
  12438. else {
  12439. if (pointer.buffer !== buffer) {
  12440. pointer.buffer = buffer;
  12441. changed = true;
  12442. }
  12443. if (pointer.size !== size) {
  12444. pointer.size = size;
  12445. changed = true;
  12446. }
  12447. if (pointer.type !== type) {
  12448. pointer.type = type;
  12449. changed = true;
  12450. }
  12451. if (pointer.normalized !== normalized) {
  12452. pointer.normalized = normalized;
  12453. changed = true;
  12454. }
  12455. if (pointer.stride !== stride) {
  12456. pointer.stride = stride;
  12457. changed = true;
  12458. }
  12459. if (pointer.offset !== offset) {
  12460. pointer.offset = offset;
  12461. changed = true;
  12462. }
  12463. }
  12464. if (changed || this._vaoRecordInProgress) {
  12465. this.bindArrayBuffer(buffer);
  12466. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12467. }
  12468. };
  12469. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12470. if (indexBuffer == null) {
  12471. return;
  12472. }
  12473. if (this._cachedIndexBuffer !== indexBuffer) {
  12474. this._cachedIndexBuffer = indexBuffer;
  12475. this.bindIndexBuffer(indexBuffer);
  12476. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12477. }
  12478. };
  12479. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12480. var attributes = effect.getAttributesNames();
  12481. if (!this._vaoRecordInProgress) {
  12482. this._unbindVertexArrayObject();
  12483. }
  12484. this.unbindAllAttributes();
  12485. for (var index = 0; index < attributes.length; index++) {
  12486. var order = effect.getAttributeLocation(index);
  12487. if (order >= 0) {
  12488. var vertexBuffer = vertexBuffers[attributes[index]];
  12489. if (!vertexBuffer) {
  12490. continue;
  12491. }
  12492. this._gl.enableVertexAttribArray(order);
  12493. if (!this._vaoRecordInProgress) {
  12494. this._vertexAttribArraysEnabled[order] = true;
  12495. }
  12496. var buffer = vertexBuffer.getBuffer();
  12497. if (buffer) {
  12498. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12499. if (vertexBuffer.getIsInstanced()) {
  12500. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12501. if (!this._vaoRecordInProgress) {
  12502. this._currentInstanceLocations.push(order);
  12503. this._currentInstanceBuffers.push(buffer);
  12504. }
  12505. }
  12506. }
  12507. }
  12508. }
  12509. };
  12510. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12511. var vao = this._gl.createVertexArray();
  12512. this._vaoRecordInProgress = true;
  12513. this._gl.bindVertexArray(vao);
  12514. this._mustWipeVertexAttributes = true;
  12515. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12516. this.bindIndexBuffer(indexBuffer);
  12517. this._vaoRecordInProgress = false;
  12518. this._gl.bindVertexArray(null);
  12519. return vao;
  12520. };
  12521. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12522. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12523. this._cachedVertexArrayObject = vertexArrayObject;
  12524. this._gl.bindVertexArray(vertexArrayObject);
  12525. this._cachedVertexBuffers = null;
  12526. this._cachedIndexBuffer = null;
  12527. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12528. this._mustWipeVertexAttributes = true;
  12529. }
  12530. };
  12531. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12532. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12533. this._cachedVertexBuffers = vertexBuffer;
  12534. this._cachedEffectForVertexBuffers = effect;
  12535. var attributesCount = effect.getAttributesCount();
  12536. this._unbindVertexArrayObject();
  12537. this.unbindAllAttributes();
  12538. var offset = 0;
  12539. for (var index = 0; index < attributesCount; index++) {
  12540. if (index < vertexDeclaration.length) {
  12541. var order = effect.getAttributeLocation(index);
  12542. if (order >= 0) {
  12543. this._gl.enableVertexAttribArray(order);
  12544. this._vertexAttribArraysEnabled[order] = true;
  12545. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12546. }
  12547. offset += vertexDeclaration[index] * 4;
  12548. }
  12549. }
  12550. }
  12551. this._bindIndexBufferWithCache(indexBuffer);
  12552. };
  12553. Engine.prototype._unbindVertexArrayObject = function () {
  12554. if (!this._cachedVertexArrayObject) {
  12555. return;
  12556. }
  12557. this._cachedVertexArrayObject = null;
  12558. this._gl.bindVertexArray(null);
  12559. };
  12560. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12561. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12562. this._cachedVertexBuffers = vertexBuffers;
  12563. this._cachedEffectForVertexBuffers = effect;
  12564. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12565. }
  12566. this._bindIndexBufferWithCache(indexBuffer);
  12567. };
  12568. Engine.prototype.unbindInstanceAttributes = function () {
  12569. var boundBuffer;
  12570. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12571. var instancesBuffer = this._currentInstanceBuffers[i];
  12572. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12573. boundBuffer = instancesBuffer;
  12574. this.bindArrayBuffer(instancesBuffer);
  12575. }
  12576. var offsetLocation = this._currentInstanceLocations[i];
  12577. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12578. }
  12579. this._currentInstanceBuffers.length = 0;
  12580. this._currentInstanceLocations.length = 0;
  12581. };
  12582. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12583. this._gl.deleteVertexArray(vao);
  12584. };
  12585. Engine.prototype._releaseBuffer = function (buffer) {
  12586. buffer.references--;
  12587. if (buffer.references === 0) {
  12588. this._gl.deleteBuffer(buffer);
  12589. return true;
  12590. }
  12591. return false;
  12592. };
  12593. Engine.prototype.createInstancesBuffer = function (capacity) {
  12594. var buffer = this._gl.createBuffer();
  12595. if (!buffer) {
  12596. throw new Error("Unable to create instance buffer");
  12597. }
  12598. buffer.capacity = capacity;
  12599. this.bindArrayBuffer(buffer);
  12600. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12601. return buffer;
  12602. };
  12603. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12604. this._gl.deleteBuffer(buffer);
  12605. };
  12606. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12607. this.bindArrayBuffer(instancesBuffer);
  12608. if (data) {
  12609. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12610. }
  12611. if (offsetLocations[0].index !== undefined) {
  12612. var stride = 0;
  12613. for (var i = 0; i < offsetLocations.length; i++) {
  12614. var ai = offsetLocations[i];
  12615. stride += ai.attributeSize * 4;
  12616. }
  12617. for (var i = 0; i < offsetLocations.length; i++) {
  12618. var ai = offsetLocations[i];
  12619. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12620. this._gl.enableVertexAttribArray(ai.index);
  12621. this._vertexAttribArraysEnabled[ai.index] = true;
  12622. }
  12623. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12624. this._gl.vertexAttribDivisor(ai.index, 1);
  12625. this._currentInstanceLocations.push(ai.index);
  12626. this._currentInstanceBuffers.push(instancesBuffer);
  12627. }
  12628. }
  12629. else {
  12630. for (var index = 0; index < 4; index++) {
  12631. var offsetLocation = offsetLocations[index];
  12632. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12633. this._gl.enableVertexAttribArray(offsetLocation);
  12634. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12635. }
  12636. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12637. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12638. this._currentInstanceLocations.push(offsetLocation);
  12639. this._currentInstanceBuffers.push(instancesBuffer);
  12640. }
  12641. }
  12642. };
  12643. Engine.prototype.applyStates = function () {
  12644. this._depthCullingState.apply(this._gl);
  12645. this._stencilState.apply(this._gl);
  12646. this._alphaState.apply(this._gl);
  12647. };
  12648. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12649. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12650. };
  12651. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12652. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12653. };
  12654. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12655. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12656. };
  12657. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12658. // Apply states
  12659. this.applyStates();
  12660. this._drawCalls.addCount(1, false);
  12661. // Render
  12662. var drawMode = this._drawMode(fillMode);
  12663. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12664. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12665. if (instancesCount) {
  12666. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12667. }
  12668. else {
  12669. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12670. }
  12671. };
  12672. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12673. // Apply states
  12674. this.applyStates();
  12675. this._drawCalls.addCount(1, false);
  12676. var drawMode = this._drawMode(fillMode);
  12677. if (instancesCount) {
  12678. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12679. }
  12680. else {
  12681. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12682. }
  12683. };
  12684. Engine.prototype._drawMode = function (fillMode) {
  12685. switch (fillMode) {
  12686. // Triangle views
  12687. case BABYLON.Material.TriangleFillMode:
  12688. return this._gl.TRIANGLES;
  12689. case BABYLON.Material.PointFillMode:
  12690. return this._gl.POINTS;
  12691. case BABYLON.Material.WireFrameFillMode:
  12692. return this._gl.LINES;
  12693. // Draw modes
  12694. case BABYLON.Material.PointListDrawMode:
  12695. return this._gl.POINTS;
  12696. case BABYLON.Material.LineListDrawMode:
  12697. return this._gl.LINES;
  12698. case BABYLON.Material.LineLoopDrawMode:
  12699. return this._gl.LINE_LOOP;
  12700. case BABYLON.Material.LineStripDrawMode:
  12701. return this._gl.LINE_STRIP;
  12702. case BABYLON.Material.TriangleStripDrawMode:
  12703. return this._gl.TRIANGLE_STRIP;
  12704. case BABYLON.Material.TriangleFanDrawMode:
  12705. return this._gl.TRIANGLE_FAN;
  12706. default:
  12707. return this._gl.TRIANGLES;
  12708. }
  12709. };
  12710. // Shaders
  12711. Engine.prototype._releaseEffect = function (effect) {
  12712. if (this._compiledEffects[effect._key]) {
  12713. delete this._compiledEffects[effect._key];
  12714. this._deleteProgram(effect.getProgram());
  12715. }
  12716. };
  12717. Engine.prototype._deleteProgram = function (program) {
  12718. if (program) {
  12719. program.__SPECTOR_rebuildProgram = null;
  12720. if (program.transformFeedback) {
  12721. this.deleteTransformFeedback(program.transformFeedback);
  12722. program.transformFeedback = null;
  12723. }
  12724. this._gl.deleteProgram(program);
  12725. }
  12726. };
  12727. /**
  12728. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12729. * @param samplers An array of string used to represent textures
  12730. */
  12731. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12732. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12733. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12734. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12735. if (this._compiledEffects[name]) {
  12736. var compiledEffect = this._compiledEffects[name];
  12737. if (onCompiled && compiledEffect.isReady()) {
  12738. onCompiled(compiledEffect);
  12739. }
  12740. return compiledEffect;
  12741. }
  12742. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12743. effect._key = name;
  12744. this._compiledEffects[name] = effect;
  12745. return effect;
  12746. };
  12747. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12748. if (uniformsNames === void 0) { uniformsNames = []; }
  12749. if (samplers === void 0) { samplers = []; }
  12750. if (defines === void 0) { defines = ""; }
  12751. return this.createEffect({
  12752. vertex: "particles",
  12753. fragmentElement: fragmentName
  12754. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12755. };
  12756. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12757. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12758. context = context || this._gl;
  12759. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12760. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12761. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12762. };
  12763. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12764. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12765. context = context || this._gl;
  12766. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12767. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12768. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12769. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12770. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12771. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12772. return program;
  12773. };
  12774. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12775. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12776. var shaderProgram = context.createProgram();
  12777. if (!shaderProgram) {
  12778. throw new Error("Unable to create program");
  12779. }
  12780. context.attachShader(shaderProgram, vertexShader);
  12781. context.attachShader(shaderProgram, fragmentShader);
  12782. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12783. var transformFeedback = this.createTransformFeedback();
  12784. this.bindTransformFeedback(transformFeedback);
  12785. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12786. shaderProgram.transformFeedback = transformFeedback;
  12787. }
  12788. context.linkProgram(shaderProgram);
  12789. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12790. this.bindTransformFeedback(null);
  12791. }
  12792. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12793. if (!linked) {
  12794. context.validateProgram(shaderProgram);
  12795. var error = context.getProgramInfoLog(shaderProgram);
  12796. if (error) {
  12797. throw new Error(error);
  12798. }
  12799. }
  12800. context.deleteShader(vertexShader);
  12801. context.deleteShader(fragmentShader);
  12802. return shaderProgram;
  12803. };
  12804. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12805. var results = new Array();
  12806. for (var index = 0; index < uniformsNames.length; index++) {
  12807. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12808. }
  12809. return results;
  12810. };
  12811. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12812. var results = [];
  12813. for (var index = 0; index < attributesNames.length; index++) {
  12814. try {
  12815. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12816. }
  12817. catch (e) {
  12818. results.push(-1);
  12819. }
  12820. }
  12821. return results;
  12822. };
  12823. Engine.prototype.enableEffect = function (effect) {
  12824. if (!effect) {
  12825. return;
  12826. }
  12827. // Use program
  12828. this.bindSamplers(effect);
  12829. this._currentEffect = effect;
  12830. if (effect.onBind) {
  12831. effect.onBind(effect);
  12832. }
  12833. effect.onBindObservable.notifyObservers(effect);
  12834. };
  12835. Engine.prototype.setIntArray = function (uniform, array) {
  12836. if (!uniform)
  12837. return;
  12838. this._gl.uniform1iv(uniform, array);
  12839. };
  12840. Engine.prototype.setIntArray2 = function (uniform, array) {
  12841. if (!uniform || array.length % 2 !== 0)
  12842. return;
  12843. this._gl.uniform2iv(uniform, array);
  12844. };
  12845. Engine.prototype.setIntArray3 = function (uniform, array) {
  12846. if (!uniform || array.length % 3 !== 0)
  12847. return;
  12848. this._gl.uniform3iv(uniform, array);
  12849. };
  12850. Engine.prototype.setIntArray4 = function (uniform, array) {
  12851. if (!uniform || array.length % 4 !== 0)
  12852. return;
  12853. this._gl.uniform4iv(uniform, array);
  12854. };
  12855. Engine.prototype.setFloatArray = function (uniform, array) {
  12856. if (!uniform)
  12857. return;
  12858. this._gl.uniform1fv(uniform, array);
  12859. };
  12860. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12861. if (!uniform || array.length % 2 !== 0)
  12862. return;
  12863. this._gl.uniform2fv(uniform, array);
  12864. };
  12865. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12866. if (!uniform || array.length % 3 !== 0)
  12867. return;
  12868. this._gl.uniform3fv(uniform, array);
  12869. };
  12870. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12871. if (!uniform || array.length % 4 !== 0)
  12872. return;
  12873. this._gl.uniform4fv(uniform, array);
  12874. };
  12875. Engine.prototype.setArray = function (uniform, array) {
  12876. if (!uniform)
  12877. return;
  12878. this._gl.uniform1fv(uniform, array);
  12879. };
  12880. Engine.prototype.setArray2 = function (uniform, array) {
  12881. if (!uniform || array.length % 2 !== 0)
  12882. return;
  12883. this._gl.uniform2fv(uniform, array);
  12884. };
  12885. Engine.prototype.setArray3 = function (uniform, array) {
  12886. if (!uniform || array.length % 3 !== 0)
  12887. return;
  12888. this._gl.uniform3fv(uniform, array);
  12889. };
  12890. Engine.prototype.setArray4 = function (uniform, array) {
  12891. if (!uniform || array.length % 4 !== 0)
  12892. return;
  12893. this._gl.uniform4fv(uniform, array);
  12894. };
  12895. Engine.prototype.setMatrices = function (uniform, matrices) {
  12896. if (!uniform)
  12897. return;
  12898. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12899. };
  12900. Engine.prototype.setMatrix = function (uniform, matrix) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12904. };
  12905. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12906. if (!uniform)
  12907. return;
  12908. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12909. };
  12910. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12911. if (!uniform)
  12912. return;
  12913. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12914. };
  12915. Engine.prototype.setInt = function (uniform, value) {
  12916. if (!uniform)
  12917. return;
  12918. this._gl.uniform1i(uniform, value);
  12919. };
  12920. Engine.prototype.setFloat = function (uniform, value) {
  12921. if (!uniform)
  12922. return;
  12923. this._gl.uniform1f(uniform, value);
  12924. };
  12925. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12926. if (!uniform)
  12927. return;
  12928. this._gl.uniform2f(uniform, x, y);
  12929. };
  12930. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12931. if (!uniform)
  12932. return;
  12933. this._gl.uniform3f(uniform, x, y, z);
  12934. };
  12935. Engine.prototype.setBool = function (uniform, bool) {
  12936. if (!uniform)
  12937. return;
  12938. this._gl.uniform1i(uniform, bool);
  12939. };
  12940. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12941. if (!uniform)
  12942. return;
  12943. this._gl.uniform4f(uniform, x, y, z, w);
  12944. };
  12945. Engine.prototype.setColor3 = function (uniform, color3) {
  12946. if (!uniform)
  12947. return;
  12948. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12949. };
  12950. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12951. if (!uniform)
  12952. return;
  12953. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12954. };
  12955. /**
  12956. * Sets a Color4 on a uniform variable
  12957. * @param uniform defines the uniform location
  12958. * @param color4 defines the value to be set
  12959. */
  12960. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12961. if (!uniform)
  12962. return;
  12963. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12964. };
  12965. // States
  12966. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12967. if (zOffset === void 0) { zOffset = 0; }
  12968. if (reverseSide === void 0) { reverseSide = false; }
  12969. // Culling
  12970. if (this._depthCullingState.cull !== culling || force) {
  12971. this._depthCullingState.cull = culling;
  12972. }
  12973. // Cull face
  12974. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12975. if (this._depthCullingState.cullFace !== cullFace || force) {
  12976. this._depthCullingState.cullFace = cullFace;
  12977. }
  12978. // Z offset
  12979. this.setZOffset(zOffset);
  12980. // Front face
  12981. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12982. if (this._depthCullingState.frontFace !== frontFace || force) {
  12983. this._depthCullingState.frontFace = frontFace;
  12984. }
  12985. };
  12986. Engine.prototype.setZOffset = function (value) {
  12987. this._depthCullingState.zOffset = value;
  12988. };
  12989. Engine.prototype.getZOffset = function () {
  12990. return this._depthCullingState.zOffset;
  12991. };
  12992. Engine.prototype.setDepthBuffer = function (enable) {
  12993. this._depthCullingState.depthTest = enable;
  12994. };
  12995. Engine.prototype.getDepthWrite = function () {
  12996. return this._depthCullingState.depthMask;
  12997. };
  12998. Engine.prototype.setDepthWrite = function (enable) {
  12999. this._depthCullingState.depthMask = enable;
  13000. };
  13001. Engine.prototype.setColorWrite = function (enable) {
  13002. this._gl.colorMask(enable, enable, enable, enable);
  13003. this._colorWrite = enable;
  13004. };
  13005. Engine.prototype.getColorWrite = function () {
  13006. return this._colorWrite;
  13007. };
  13008. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13009. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13010. };
  13011. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13012. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13013. if (this._alphaMode === mode) {
  13014. return;
  13015. }
  13016. switch (mode) {
  13017. case Engine.ALPHA_DISABLE:
  13018. this._alphaState.alphaBlend = false;
  13019. break;
  13020. case Engine.ALPHA_PREMULTIPLIED:
  13021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13022. this._alphaState.alphaBlend = true;
  13023. break;
  13024. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13025. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13026. this._alphaState.alphaBlend = true;
  13027. break;
  13028. case Engine.ALPHA_COMBINE:
  13029. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13030. this._alphaState.alphaBlend = true;
  13031. break;
  13032. case Engine.ALPHA_ONEONE:
  13033. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13034. this._alphaState.alphaBlend = true;
  13035. break;
  13036. case Engine.ALPHA_ADD:
  13037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13038. this._alphaState.alphaBlend = true;
  13039. break;
  13040. case Engine.ALPHA_SUBTRACT:
  13041. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13042. this._alphaState.alphaBlend = true;
  13043. break;
  13044. case Engine.ALPHA_MULTIPLY:
  13045. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13046. this._alphaState.alphaBlend = true;
  13047. break;
  13048. case Engine.ALPHA_MAXIMIZED:
  13049. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13050. this._alphaState.alphaBlend = true;
  13051. break;
  13052. case Engine.ALPHA_INTERPOLATE:
  13053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13054. this._alphaState.alphaBlend = true;
  13055. break;
  13056. case Engine.ALPHA_SCREENMODE:
  13057. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13058. this._alphaState.alphaBlend = true;
  13059. break;
  13060. }
  13061. if (!noDepthWriteChange) {
  13062. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13063. }
  13064. this._alphaMode = mode;
  13065. };
  13066. Engine.prototype.getAlphaMode = function () {
  13067. return this._alphaMode;
  13068. };
  13069. // Textures
  13070. Engine.prototype.wipeCaches = function (bruteForce) {
  13071. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13072. return;
  13073. }
  13074. this._currentEffect = null;
  13075. // 6/8/2017: deltakosh: Should not be required anymore.
  13076. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13077. if (bruteForce) {
  13078. this.resetTextureCache();
  13079. this._currentProgram = null;
  13080. this._stencilState.reset();
  13081. this._depthCullingState.reset();
  13082. this.setDepthFunctionToLessOrEqual();
  13083. this._alphaState.reset();
  13084. }
  13085. this._resetVertexBufferBinding();
  13086. this._cachedIndexBuffer = null;
  13087. this._cachedEffectForVertexBuffers = null;
  13088. this._unbindVertexArrayObject();
  13089. this.bindIndexBuffer(null);
  13090. };
  13091. /**
  13092. * Set the compressed texture format to use, based on the formats you have, and the formats
  13093. * supported by the hardware / browser.
  13094. *
  13095. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13096. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13097. * to API arguments needed to compressed textures. This puts the burden on the container
  13098. * generator to house the arcane code for determining these for current & future formats.
  13099. *
  13100. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13101. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13102. *
  13103. * Note: The result of this call is not taken into account when a texture is base64.
  13104. *
  13105. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13106. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13107. *
  13108. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13109. * @returns The extension selected.
  13110. */
  13111. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13112. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13113. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13114. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13115. return this._textureFormatInUse = this._texturesSupported[i];
  13116. }
  13117. }
  13118. }
  13119. // actively set format to nothing, to allow this to be called more than once
  13120. // and possibly fail the 2nd time
  13121. this._textureFormatInUse = null;
  13122. return null;
  13123. };
  13124. Engine.prototype._createTexture = function () {
  13125. var texture = this._gl.createTexture();
  13126. if (!texture) {
  13127. throw new Error("Unable to create texture");
  13128. }
  13129. return texture;
  13130. };
  13131. /**
  13132. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13133. * @param {string} urlArg- This contains one of the following:
  13134. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13135. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13136. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13137. *
  13138. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13139. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13140. * @param {Scene} scene- Needed for loading to the correct scene.
  13141. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13142. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13143. * @param {callback} onError- Optional callback to be called upon failure.
  13144. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13145. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13146. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13147. *
  13148. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13149. */
  13150. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13151. var _this = this;
  13152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13153. if (onLoad === void 0) { onLoad = null; }
  13154. if (onError === void 0) { onError = null; }
  13155. if (buffer === void 0) { buffer = null; }
  13156. if (fallBack === void 0) { fallBack = null; }
  13157. if (format === void 0) { format = null; }
  13158. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13159. var fromData = url.substr(0, 5) === "data:";
  13160. var fromBlob = url.substr(0, 5) === "blob:";
  13161. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13162. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13163. // establish the file extension, if possible
  13164. var lastDot = url.lastIndexOf('.');
  13165. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13166. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13167. var isTGA = (extension.indexOf(".tga") === 0);
  13168. // determine if a ktx file should be substituted
  13169. var isKTX = false;
  13170. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13171. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13172. isKTX = true;
  13173. }
  13174. if (scene) {
  13175. scene._addPendingData(texture);
  13176. }
  13177. texture.url = url;
  13178. texture.generateMipMaps = !noMipmap;
  13179. texture.samplingMode = samplingMode;
  13180. texture.invertY = invertY;
  13181. if (!this._doNotHandleContextLost) {
  13182. // Keep a link to the buffer only if we plan to handle context lost
  13183. texture._buffer = buffer;
  13184. }
  13185. var onLoadObserver = null;
  13186. if (onLoad && !fallBack) {
  13187. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13188. }
  13189. if (!fallBack)
  13190. this._internalTexturesCache.push(texture);
  13191. var onerror = function (message, exception) {
  13192. if (scene) {
  13193. scene._removePendingData(texture);
  13194. }
  13195. if (onLoadObserver) {
  13196. texture.onLoadedObservable.remove(onLoadObserver);
  13197. }
  13198. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13199. if (isKTX) {
  13200. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13201. }
  13202. else if (BABYLON.Tools.UseFallbackTexture) {
  13203. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13204. }
  13205. if (onError) {
  13206. onError(message || "Unknown error", exception);
  13207. }
  13208. };
  13209. var callback = null;
  13210. // processing for non-image formats
  13211. if (isKTX || isTGA || isDDS) {
  13212. if (isKTX) {
  13213. callback = function (data) {
  13214. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13215. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13216. ktx.uploadLevels(_this._gl, !noMipmap);
  13217. return false;
  13218. }, samplingMode);
  13219. };
  13220. }
  13221. else if (isTGA) {
  13222. callback = function (arrayBuffer) {
  13223. var data = new Uint8Array(arrayBuffer);
  13224. var header = BABYLON.TGATools.GetTGAHeader(data);
  13225. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13226. BABYLON.TGATools.UploadContent(_this._gl, data);
  13227. return false;
  13228. }, samplingMode);
  13229. };
  13230. }
  13231. else if (isDDS) {
  13232. callback = function (data) {
  13233. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13234. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13235. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13236. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13237. return false;
  13238. }, samplingMode);
  13239. };
  13240. }
  13241. if (!buffer) {
  13242. this._loadFile(url, function (data) {
  13243. if (callback) {
  13244. callback(data);
  13245. }
  13246. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13247. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13248. });
  13249. }
  13250. else {
  13251. if (callback) {
  13252. callback(buffer);
  13253. }
  13254. }
  13255. // image format processing
  13256. }
  13257. else {
  13258. var onload = function (img) {
  13259. if (fromBlob && !_this._doNotHandleContextLost) {
  13260. // We need to store the image if we need to rebuild the texture
  13261. // in case of a webgl context lost
  13262. texture._buffer = img;
  13263. }
  13264. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13265. var gl = _this._gl;
  13266. var isPot = (img.width === potWidth && img.height === potHeight);
  13267. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13268. if (isPot) {
  13269. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13270. return false;
  13271. }
  13272. // Using shaders to rescale because canvas.drawImage is lossy
  13273. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13274. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13275. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13280. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13281. _this._releaseTexture(source);
  13282. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13283. continuationCallback();
  13284. });
  13285. return true;
  13286. }, samplingMode);
  13287. };
  13288. if (!fromData || isBase64)
  13289. if (buffer instanceof HTMLImageElement) {
  13290. onload(buffer);
  13291. }
  13292. else {
  13293. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13294. }
  13295. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13296. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13297. else
  13298. onload(buffer);
  13299. }
  13300. return texture;
  13301. };
  13302. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13303. var _this = this;
  13304. var rtt = this.createRenderTargetTexture({
  13305. width: destination.width,
  13306. height: destination.height,
  13307. }, {
  13308. generateMipMaps: false,
  13309. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13310. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13311. generateDepthBuffer: false,
  13312. generateStencilBuffer: false
  13313. });
  13314. if (!this._rescalePostProcess) {
  13315. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13316. }
  13317. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13318. _this._rescalePostProcess.onApply = function (effect) {
  13319. effect._bindTexture("textureSampler", source);
  13320. };
  13321. var hostingScene = scene;
  13322. if (!hostingScene) {
  13323. hostingScene = _this.scenes[_this.scenes.length - 1];
  13324. }
  13325. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13326. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13327. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13328. _this.unBindFramebuffer(rtt);
  13329. _this._releaseTexture(rtt);
  13330. if (onComplete) {
  13331. onComplete();
  13332. }
  13333. });
  13334. };
  13335. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13336. if (compression === void 0) { compression = null; }
  13337. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13338. if (!texture) {
  13339. return;
  13340. }
  13341. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13342. var internalFormat = this._getInternalFormat(format);
  13343. var textureType = this._getWebGLTextureType(type);
  13344. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13345. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13346. if (!this._doNotHandleContextLost) {
  13347. texture._bufferView = data;
  13348. texture.format = format;
  13349. texture.type = type;
  13350. texture.invertY = invertY;
  13351. texture._compression = compression;
  13352. }
  13353. if (texture.width % 4 !== 0) {
  13354. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13355. }
  13356. if (compression && data) {
  13357. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13358. }
  13359. else {
  13360. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13361. }
  13362. if (texture.generateMipMaps) {
  13363. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13364. }
  13365. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13366. // this.resetTextureCache();
  13367. texture.isReady = true;
  13368. };
  13369. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13370. if (compression === void 0) { compression = null; }
  13371. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13372. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13373. texture.baseWidth = width;
  13374. texture.baseHeight = height;
  13375. texture.width = width;
  13376. texture.height = height;
  13377. texture.format = format;
  13378. texture.generateMipMaps = generateMipMaps;
  13379. texture.samplingMode = samplingMode;
  13380. texture.invertY = invertY;
  13381. texture._compression = compression;
  13382. texture.type = type;
  13383. if (!this._doNotHandleContextLost) {
  13384. texture._bufferView = data;
  13385. }
  13386. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13387. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13388. // Filters
  13389. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13390. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13391. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13392. if (generateMipMaps) {
  13393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13394. }
  13395. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13396. this._internalTexturesCache.push(texture);
  13397. return texture;
  13398. };
  13399. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13400. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13401. texture.baseWidth = width;
  13402. texture.baseHeight = height;
  13403. if (generateMipMaps) {
  13404. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13405. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13406. }
  13407. // this.resetTextureCache();
  13408. texture.width = width;
  13409. texture.height = height;
  13410. texture.isReady = false;
  13411. texture.generateMipMaps = generateMipMaps;
  13412. texture.samplingMode = samplingMode;
  13413. this.updateTextureSamplingMode(samplingMode, texture);
  13414. this._internalTexturesCache.push(texture);
  13415. return texture;
  13416. };
  13417. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13418. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13419. if (texture.isCube) {
  13420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13421. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13422. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13423. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13424. }
  13425. else if (texture.is3D) {
  13426. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13427. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13428. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13429. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13430. }
  13431. else {
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13433. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13434. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13435. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13436. }
  13437. texture.samplingMode = samplingMode;
  13438. };
  13439. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13440. if (premulAlpha === void 0) { premulAlpha = false; }
  13441. if (!texture) {
  13442. return;
  13443. }
  13444. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13445. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13446. if (premulAlpha) {
  13447. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13448. }
  13449. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13450. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13451. if (texture.generateMipMaps) {
  13452. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13453. }
  13454. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13455. if (premulAlpha) {
  13456. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13457. }
  13458. texture.isReady = true;
  13459. };
  13460. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13461. if (!texture || texture._isDisabled) {
  13462. return;
  13463. }
  13464. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13465. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13466. try {
  13467. // Testing video texture support
  13468. if (this._videoTextureSupported === undefined) {
  13469. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13470. if (this._gl.getError() !== 0) {
  13471. this._videoTextureSupported = false;
  13472. }
  13473. else {
  13474. this._videoTextureSupported = true;
  13475. }
  13476. }
  13477. // Copy video through the current working canvas if video texture is not supported
  13478. if (!this._videoTextureSupported) {
  13479. if (!texture._workingCanvas) {
  13480. texture._workingCanvas = document.createElement("canvas");
  13481. var context = texture._workingCanvas.getContext("2d");
  13482. if (!context) {
  13483. throw new Error("Unable to get 2d context");
  13484. }
  13485. texture._workingContext = context;
  13486. texture._workingCanvas.width = texture.width;
  13487. texture._workingCanvas.height = texture.height;
  13488. }
  13489. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13490. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13491. }
  13492. else {
  13493. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13494. }
  13495. if (texture.generateMipMaps) {
  13496. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13497. }
  13498. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13499. // this.resetTextureCache();
  13500. texture.isReady = true;
  13501. }
  13502. catch (ex) {
  13503. // Something unexpected
  13504. // Let's disable the texture
  13505. texture._isDisabled = true;
  13506. }
  13507. };
  13508. /**
  13509. * Updates a depth texture Comparison Mode and Function.
  13510. * If the comparison Function is equal to 0, the mode will be set to none.
  13511. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13512. * @param texture The texture to set the comparison function for
  13513. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13514. */
  13515. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13516. if (this.webGLVersion === 1) {
  13517. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13518. return;
  13519. }
  13520. var gl = this._gl;
  13521. if (texture.isCube) {
  13522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13523. if (comparisonFunction === 0) {
  13524. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13525. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13526. }
  13527. else {
  13528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13530. }
  13531. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13532. }
  13533. else {
  13534. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13535. if (comparisonFunction === 0) {
  13536. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13537. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13538. }
  13539. else {
  13540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13542. }
  13543. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13544. }
  13545. texture._comparisonFunction = comparisonFunction;
  13546. };
  13547. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13548. var width = size.width || size;
  13549. var height = size.height || size;
  13550. internalTexture.baseWidth = width;
  13551. internalTexture.baseHeight = height;
  13552. internalTexture.width = width;
  13553. internalTexture.height = height;
  13554. internalTexture.isReady = true;
  13555. internalTexture.samples = 1;
  13556. internalTexture.generateMipMaps = false;
  13557. internalTexture._generateDepthBuffer = true;
  13558. internalTexture._generateStencilBuffer = generateStencil;
  13559. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13560. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13561. internalTexture._comparisonFunction = comparisonFunction;
  13562. var gl = this._gl;
  13563. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13564. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13565. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13566. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13567. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13568. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13569. if (comparisonFunction === 0) {
  13570. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13571. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13572. }
  13573. else {
  13574. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13575. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13576. }
  13577. };
  13578. /**
  13579. * Creates a depth stencil texture.
  13580. * This is only available in WebGL 2 or with the depth texture extension available.
  13581. * @param size The size of face edge in the texture.
  13582. * @param options The options defining the texture.
  13583. * @returns The texture
  13584. */
  13585. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13586. if (options.isCube) {
  13587. var width = size.width || size;
  13588. return this._createDepthStencilCubeTexture(width, options);
  13589. }
  13590. else {
  13591. return this._createDepthStencilTexture(size, options);
  13592. }
  13593. };
  13594. /**
  13595. * Creates a depth stencil texture.
  13596. * This is only available in WebGL 2 or with the depth texture extension available.
  13597. * @param size The size of face edge in the texture.
  13598. * @param options The options defining the texture.
  13599. * @returns The texture
  13600. */
  13601. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13602. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13603. if (!this._caps.depthTextureExtension) {
  13604. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13605. return internalTexture;
  13606. }
  13607. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13608. var gl = this._gl;
  13609. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13610. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13611. if (this.webGLVersion > 1) {
  13612. if (internalOptions.generateStencil) {
  13613. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13614. }
  13615. else {
  13616. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13617. }
  13618. }
  13619. else {
  13620. if (internalOptions.generateStencil) {
  13621. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13622. }
  13623. else {
  13624. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13625. }
  13626. }
  13627. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13628. return internalTexture;
  13629. };
  13630. /**
  13631. * Creates a depth stencil cube texture.
  13632. * This is only available in WebGL 2.
  13633. * @param size The size of face edge in the cube texture.
  13634. * @param options The options defining the cube texture.
  13635. * @returns The cube texture
  13636. */
  13637. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13638. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13639. internalTexture.isCube = true;
  13640. if (this.webGLVersion === 1) {
  13641. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13642. return internalTexture;
  13643. }
  13644. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13645. var gl = this._gl;
  13646. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13647. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13648. // Create the depth/stencil buffer
  13649. for (var face = 0; face < 6; face++) {
  13650. if (internalOptions.generateStencil) {
  13651. 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);
  13652. }
  13653. else {
  13654. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13655. }
  13656. }
  13657. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13658. return internalTexture;
  13659. };
  13660. /**
  13661. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13662. * @param renderTarget The render target to set the frame buffer for
  13663. */
  13664. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13665. // Create the framebuffer
  13666. var internalTexture = renderTarget.getInternalTexture();
  13667. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13668. return;
  13669. }
  13670. var gl = this._gl;
  13671. var depthStencilTexture = renderTarget.depthStencilTexture;
  13672. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13673. if (depthStencilTexture.isCube) {
  13674. if (depthStencilTexture._generateStencilBuffer) {
  13675. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13676. }
  13677. else {
  13678. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13679. }
  13680. }
  13681. else {
  13682. if (depthStencilTexture._generateStencilBuffer) {
  13683. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13684. }
  13685. else {
  13686. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13687. }
  13688. }
  13689. this.bindUnboundFramebuffer(null);
  13690. };
  13691. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13692. var fullOptions = new RenderTargetCreationOptions();
  13693. if (options !== undefined && typeof options === "object") {
  13694. fullOptions.generateMipMaps = options.generateMipMaps;
  13695. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13696. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13697. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13698. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13699. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13700. }
  13701. else {
  13702. fullOptions.generateMipMaps = options;
  13703. fullOptions.generateDepthBuffer = true;
  13704. fullOptions.generateStencilBuffer = false;
  13705. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13706. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13707. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13708. }
  13709. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13710. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13711. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13712. }
  13713. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13714. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13715. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13716. }
  13717. var gl = this._gl;
  13718. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13719. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13720. var width = size.width || size;
  13721. var height = size.height || size;
  13722. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13723. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13724. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13725. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13726. }
  13727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13728. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13729. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13731. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13732. // Create the framebuffer
  13733. var framebuffer = gl.createFramebuffer();
  13734. this.bindUnboundFramebuffer(framebuffer);
  13735. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13736. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13737. if (fullOptions.generateMipMaps) {
  13738. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13739. }
  13740. // Unbind
  13741. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13742. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13743. this.bindUnboundFramebuffer(null);
  13744. texture._framebuffer = framebuffer;
  13745. texture.baseWidth = width;
  13746. texture.baseHeight = height;
  13747. texture.width = width;
  13748. texture.height = height;
  13749. texture.isReady = true;
  13750. texture.samples = 1;
  13751. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13752. texture.samplingMode = fullOptions.samplingMode;
  13753. texture.type = fullOptions.type;
  13754. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13755. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13756. // this.resetTextureCache();
  13757. this._internalTexturesCache.push(texture);
  13758. return texture;
  13759. };
  13760. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13761. var generateMipMaps = false;
  13762. var generateDepthBuffer = true;
  13763. var generateStencilBuffer = false;
  13764. var generateDepthTexture = false;
  13765. var textureCount = 1;
  13766. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13767. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13768. var types = [], samplingModes = [];
  13769. if (options !== undefined) {
  13770. generateMipMaps = options.generateMipMaps;
  13771. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13772. generateStencilBuffer = options.generateStencilBuffer;
  13773. generateDepthTexture = options.generateDepthTexture;
  13774. textureCount = options.textureCount || 1;
  13775. if (options.types) {
  13776. types = options.types;
  13777. }
  13778. if (options.samplingModes) {
  13779. samplingModes = options.samplingModes;
  13780. }
  13781. }
  13782. var gl = this._gl;
  13783. // Create the framebuffer
  13784. var framebuffer = gl.createFramebuffer();
  13785. this.bindUnboundFramebuffer(framebuffer);
  13786. var width = size.width || size;
  13787. var height = size.height || size;
  13788. var textures = [];
  13789. var attachments = [];
  13790. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13791. for (var i = 0; i < textureCount; i++) {
  13792. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13793. var type = types[i] || defaultType;
  13794. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13795. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13796. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13797. }
  13798. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13799. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13800. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13801. }
  13802. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13803. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13804. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13805. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13806. }
  13807. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13808. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13809. textures.push(texture);
  13810. attachments.push(attachment);
  13811. gl.activeTexture(gl["TEXTURE" + i]);
  13812. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13815. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13817. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13818. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13819. if (generateMipMaps) {
  13820. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13821. }
  13822. // Unbind
  13823. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13824. texture._framebuffer = framebuffer;
  13825. texture._depthStencilBuffer = depthStencilBuffer;
  13826. texture.baseWidth = width;
  13827. texture.baseHeight = height;
  13828. texture.width = width;
  13829. texture.height = height;
  13830. texture.isReady = true;
  13831. texture.samples = 1;
  13832. texture.generateMipMaps = generateMipMaps;
  13833. texture.samplingMode = samplingMode;
  13834. texture.type = type;
  13835. texture._generateDepthBuffer = generateDepthBuffer;
  13836. texture._generateStencilBuffer = generateStencilBuffer;
  13837. texture._attachments = attachments;
  13838. this._internalTexturesCache.push(texture);
  13839. }
  13840. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13841. // Depth texture
  13842. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13843. gl.activeTexture(gl.TEXTURE0);
  13844. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13846. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13847. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13849. 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);
  13850. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13851. depthTexture._framebuffer = framebuffer;
  13852. depthTexture.baseWidth = width;
  13853. depthTexture.baseHeight = height;
  13854. depthTexture.width = width;
  13855. depthTexture.height = height;
  13856. depthTexture.isReady = true;
  13857. depthTexture.samples = 1;
  13858. depthTexture.generateMipMaps = generateMipMaps;
  13859. depthTexture.samplingMode = gl.NEAREST;
  13860. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13861. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13862. textures.push(depthTexture);
  13863. this._internalTexturesCache.push(depthTexture);
  13864. }
  13865. gl.drawBuffers(attachments);
  13866. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13867. this.bindUnboundFramebuffer(null);
  13868. this.resetTextureCache();
  13869. return textures;
  13870. };
  13871. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13872. if (samples === void 0) { samples = 1; }
  13873. var depthStencilBuffer = null;
  13874. var gl = this._gl;
  13875. // Create the depth/stencil buffer
  13876. if (generateStencilBuffer) {
  13877. depthStencilBuffer = gl.createRenderbuffer();
  13878. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13879. if (samples > 1) {
  13880. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13881. }
  13882. else {
  13883. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13884. }
  13885. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13886. }
  13887. else if (generateDepthBuffer) {
  13888. depthStencilBuffer = gl.createRenderbuffer();
  13889. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13890. if (samples > 1) {
  13891. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13892. }
  13893. else {
  13894. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13895. }
  13896. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13897. }
  13898. return depthStencilBuffer;
  13899. };
  13900. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13901. if (this.webGLVersion < 2 || !texture) {
  13902. return 1;
  13903. }
  13904. if (texture.samples === samples) {
  13905. return samples;
  13906. }
  13907. var gl = this._gl;
  13908. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13909. // Dispose previous render buffers
  13910. if (texture._depthStencilBuffer) {
  13911. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13912. texture._depthStencilBuffer = null;
  13913. }
  13914. if (texture._MSAAFramebuffer) {
  13915. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13916. texture._MSAAFramebuffer = null;
  13917. }
  13918. if (texture._MSAARenderBuffer) {
  13919. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13920. texture._MSAARenderBuffer = null;
  13921. }
  13922. if (samples > 1) {
  13923. var framebuffer = gl.createFramebuffer();
  13924. if (!framebuffer) {
  13925. throw new Error("Unable to create multi sampled framebuffer");
  13926. }
  13927. texture._MSAAFramebuffer = framebuffer;
  13928. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13929. var colorRenderbuffer = gl.createRenderbuffer();
  13930. if (!colorRenderbuffer) {
  13931. throw new Error("Unable to create multi sampled framebuffer");
  13932. }
  13933. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13934. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13935. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13936. texture._MSAARenderBuffer = colorRenderbuffer;
  13937. }
  13938. else {
  13939. this.bindUnboundFramebuffer(texture._framebuffer);
  13940. }
  13941. texture.samples = samples;
  13942. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13944. this.bindUnboundFramebuffer(null);
  13945. return samples;
  13946. };
  13947. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13948. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13949. return 1;
  13950. }
  13951. if (textures[0].samples === samples) {
  13952. return samples;
  13953. }
  13954. var gl = this._gl;
  13955. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13956. // Dispose previous render buffers
  13957. if (textures[0]._depthStencilBuffer) {
  13958. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13959. textures[0]._depthStencilBuffer = null;
  13960. }
  13961. if (textures[0]._MSAAFramebuffer) {
  13962. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13963. textures[0]._MSAAFramebuffer = null;
  13964. }
  13965. for (var i = 0; i < textures.length; i++) {
  13966. if (textures[i]._MSAARenderBuffer) {
  13967. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13968. textures[i]._MSAARenderBuffer = null;
  13969. }
  13970. }
  13971. if (samples > 1) {
  13972. var framebuffer = gl.createFramebuffer();
  13973. if (!framebuffer) {
  13974. throw new Error("Unable to create multi sampled framebuffer");
  13975. }
  13976. this.bindUnboundFramebuffer(framebuffer);
  13977. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13978. var attachments = [];
  13979. for (var i = 0; i < textures.length; i++) {
  13980. var texture = textures[i];
  13981. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13982. var colorRenderbuffer = gl.createRenderbuffer();
  13983. if (!colorRenderbuffer) {
  13984. throw new Error("Unable to create multi sampled framebuffer");
  13985. }
  13986. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13987. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13988. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13989. texture._MSAAFramebuffer = framebuffer;
  13990. texture._MSAARenderBuffer = colorRenderbuffer;
  13991. texture.samples = samples;
  13992. texture._depthStencilBuffer = depthStencilBuffer;
  13993. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13994. attachments.push(attachment);
  13995. }
  13996. gl.drawBuffers(attachments);
  13997. }
  13998. else {
  13999. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14000. }
  14001. this.bindUnboundFramebuffer(null);
  14002. return samples;
  14003. };
  14004. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14005. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14006. };
  14007. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14008. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14009. };
  14010. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14011. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14012. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14013. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14014. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14015. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14016. }
  14017. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14018. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14019. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14020. }
  14021. var gl = this._gl;
  14022. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14023. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14024. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14025. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14026. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14027. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14028. }
  14029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14032. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14033. for (var face = 0; face < 6; face++) {
  14034. 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);
  14035. }
  14036. // Create the framebuffer
  14037. var framebuffer = gl.createFramebuffer();
  14038. this.bindUnboundFramebuffer(framebuffer);
  14039. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14040. // MipMaps
  14041. if (fullOptions.generateMipMaps) {
  14042. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14043. }
  14044. // Unbind
  14045. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14046. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14047. this.bindUnboundFramebuffer(null);
  14048. texture._framebuffer = framebuffer;
  14049. texture.width = size;
  14050. texture.height = size;
  14051. texture.isReady = true;
  14052. texture.isCube = true;
  14053. texture.samples = 1;
  14054. texture.generateMipMaps = fullOptions.generateMipMaps;
  14055. texture.samplingMode = fullOptions.samplingMode;
  14056. texture.type = fullOptions.type;
  14057. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14058. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14059. this._internalTexturesCache.push(texture);
  14060. return texture;
  14061. };
  14062. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14063. var _this = this;
  14064. if (onLoad === void 0) { onLoad = null; }
  14065. if (onError === void 0) { onError = null; }
  14066. if (forcedExtension === void 0) { forcedExtension = null; }
  14067. var callback = function (loadData) {
  14068. if (!loadData) {
  14069. if (onLoad) {
  14070. onLoad(null);
  14071. }
  14072. return;
  14073. }
  14074. var texture = loadData.texture;
  14075. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14076. texture._lodGenerationScale = scale;
  14077. texture._lodGenerationOffset = offset;
  14078. if (_this._caps.textureLOD) {
  14079. // Do not add extra process if texture lod is supported.
  14080. if (onLoad) {
  14081. onLoad(texture);
  14082. }
  14083. return;
  14084. }
  14085. var mipSlices = 3;
  14086. var gl = _this._gl;
  14087. var width = loadData.width;
  14088. if (!width) {
  14089. return;
  14090. }
  14091. var textures = [];
  14092. for (var i = 0; i < mipSlices; i++) {
  14093. //compute LOD from even spacing in smoothness (matching shader calculation)
  14094. var smoothness = i / (mipSlices - 1);
  14095. var roughness = 1 - smoothness;
  14096. var minLODIndex = offset; // roughness = 0
  14097. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14098. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14099. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14100. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14101. glTextureFromLod.isCube = true;
  14102. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14105. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14107. if (loadData.isDDS) {
  14108. var info = loadData.info;
  14109. var data = loadData.data;
  14110. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14111. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14112. }
  14113. else {
  14114. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14115. }
  14116. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14117. // Wrap in a base texture for easy binding.
  14118. var lodTexture = new BABYLON.BaseTexture(scene);
  14119. lodTexture.isCube = true;
  14120. lodTexture._texture = glTextureFromLod;
  14121. glTextureFromLod.isReady = true;
  14122. textures.push(lodTexture);
  14123. }
  14124. texture._lodTextureHigh = textures[2];
  14125. texture._lodTextureMid = textures[1];
  14126. texture._lodTextureLow = textures[0];
  14127. if (onLoad) {
  14128. onLoad(texture);
  14129. }
  14130. };
  14131. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14132. };
  14133. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14134. var _this = this;
  14135. if (onLoad === void 0) { onLoad = null; }
  14136. if (onError === void 0) { onError = null; }
  14137. if (forcedExtension === void 0) { forcedExtension = null; }
  14138. var gl = this._gl;
  14139. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14140. texture.isCube = true;
  14141. texture.url = rootUrl;
  14142. texture.generateMipMaps = !noMipmap;
  14143. if (!this._doNotHandleContextLost) {
  14144. texture._extension = forcedExtension;
  14145. texture._files = files;
  14146. }
  14147. var isKTX = false;
  14148. var isDDS = false;
  14149. var lastDot = rootUrl.lastIndexOf('.');
  14150. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14151. if (this._textureFormatInUse) {
  14152. extension = this._textureFormatInUse;
  14153. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14154. isKTX = true;
  14155. }
  14156. else {
  14157. isDDS = (extension === ".dds");
  14158. }
  14159. var onerror = function (request, exception) {
  14160. if (onError && request) {
  14161. onError(request.status + " " + request.statusText, exception);
  14162. }
  14163. };
  14164. if (isKTX) {
  14165. this._loadFile(rootUrl, function (data) {
  14166. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14167. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14168. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14169. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14170. ktx.uploadLevels(_this._gl, !noMipmap);
  14171. _this.setCubeMapTextureParams(gl, loadMipmap);
  14172. texture.width = ktx.pixelWidth;
  14173. texture.height = ktx.pixelHeight;
  14174. texture.isReady = true;
  14175. }, undefined, undefined, true, onerror);
  14176. }
  14177. else if (isDDS) {
  14178. if (files && files.length === 6) {
  14179. this._cascadeLoadFiles(scene, function (imgs) {
  14180. var info;
  14181. var loadMipmap = false;
  14182. var width = 0;
  14183. for (var index = 0; index < imgs.length; index++) {
  14184. var data = imgs[index];
  14185. info = BABYLON.DDSTools.GetDDSInfo(data);
  14186. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14187. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14188. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14189. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14190. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14191. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14192. }
  14193. texture.width = info.width;
  14194. texture.height = info.height;
  14195. texture.type = info.textureType;
  14196. width = info.width;
  14197. }
  14198. _this.setCubeMapTextureParams(gl, loadMipmap);
  14199. texture.isReady = true;
  14200. if (onLoad) {
  14201. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14202. }
  14203. }, files, onError);
  14204. }
  14205. else {
  14206. this._loadFile(rootUrl, function (data) {
  14207. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14208. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14209. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14210. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14211. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14212. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14213. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14214. }
  14215. _this.setCubeMapTextureParams(gl, loadMipmap);
  14216. texture.width = info.width;
  14217. texture.height = info.height;
  14218. texture.isReady = true;
  14219. texture.type = info.textureType;
  14220. if (onLoad) {
  14221. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14222. }
  14223. }, undefined, undefined, true, onerror);
  14224. }
  14225. }
  14226. else {
  14227. if (!files) {
  14228. throw new Error("Cannot load cubemap because files were not defined");
  14229. }
  14230. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14231. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14232. var height = width;
  14233. _this._prepareWorkingCanvas();
  14234. if (!_this._workingCanvas || !_this._workingContext) {
  14235. return;
  14236. }
  14237. _this._workingCanvas.width = width;
  14238. _this._workingCanvas.height = height;
  14239. var faces = [
  14240. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14241. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14242. ];
  14243. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14244. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14245. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14246. for (var index = 0; index < faces.length; index++) {
  14247. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14248. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14249. }
  14250. if (!noMipmap) {
  14251. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14252. }
  14253. _this.setCubeMapTextureParams(gl, !noMipmap);
  14254. texture.width = width;
  14255. texture.height = height;
  14256. texture.isReady = true;
  14257. if (format) {
  14258. texture.format = format;
  14259. }
  14260. texture.onLoadedObservable.notifyObservers(texture);
  14261. texture.onLoadedObservable.clear();
  14262. if (onLoad) {
  14263. onLoad();
  14264. }
  14265. }, files, onError);
  14266. }
  14267. this._internalTexturesCache.push(texture);
  14268. return texture;
  14269. };
  14270. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14275. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14276. // this.resetTextureCache();
  14277. };
  14278. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14279. if (compression === void 0) { compression = null; }
  14280. if (level === void 0) { level = 0; }
  14281. texture._bufferViewArray = data;
  14282. texture.format = format;
  14283. texture.type = type;
  14284. texture.invertY = invertY;
  14285. texture._compression = compression;
  14286. var gl = this._gl;
  14287. var textureType = this._getWebGLTextureType(type);
  14288. var internalFormat = this._getInternalFormat(format);
  14289. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14290. var needConversion = false;
  14291. if (internalFormat === gl.RGB) {
  14292. internalFormat = gl.RGBA;
  14293. needConversion = true;
  14294. }
  14295. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14296. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14297. if (texture.width % 4 !== 0) {
  14298. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14299. }
  14300. // Data are known to be in +X +Y +Z -X -Y -Z
  14301. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14302. var faceData = data[faceIndex];
  14303. if (compression) {
  14304. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14305. }
  14306. else {
  14307. if (needConversion) {
  14308. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14309. }
  14310. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14311. }
  14312. }
  14313. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14314. if (isPot && texture.generateMipMaps && level === 0) {
  14315. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14316. }
  14317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14318. // this.resetTextureCache();
  14319. texture.isReady = true;
  14320. };
  14321. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14322. if (compression === void 0) { compression = null; }
  14323. var gl = this._gl;
  14324. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14325. texture.isCube = true;
  14326. texture.generateMipMaps = generateMipMaps;
  14327. texture.format = format;
  14328. texture.type = type;
  14329. if (!this._doNotHandleContextLost) {
  14330. texture._bufferViewArray = data;
  14331. }
  14332. var textureType = this._getWebGLTextureType(type);
  14333. var internalFormat = this._getInternalFormat(format);
  14334. if (internalFormat === gl.RGB) {
  14335. internalFormat = gl.RGBA;
  14336. }
  14337. var width = size;
  14338. var height = width;
  14339. texture.width = width;
  14340. texture.height = height;
  14341. // Double check on POT to generate Mips.
  14342. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14343. if (!isPot) {
  14344. generateMipMaps = false;
  14345. }
  14346. // Upload data if needed. The texture won't be ready until then.
  14347. if (data) {
  14348. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14349. }
  14350. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14351. // Filters
  14352. if (data && generateMipMaps) {
  14353. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14354. }
  14355. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14358. }
  14359. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14362. }
  14363. else {
  14364. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14367. }
  14368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14370. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14371. return texture;
  14372. };
  14373. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14374. var _this = this;
  14375. if (onLoad === void 0) { onLoad = null; }
  14376. if (onError === void 0) { onError = null; }
  14377. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14378. if (invertY === void 0) { invertY = false; }
  14379. var gl = this._gl;
  14380. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14381. scene._addPendingData(texture);
  14382. texture.url = url;
  14383. this._internalTexturesCache.push(texture);
  14384. var onerror = function (request, exception) {
  14385. scene._removePendingData(texture);
  14386. if (onError && request) {
  14387. onError(request.status + " " + request.statusText, exception);
  14388. }
  14389. };
  14390. var internalCallback = function (data) {
  14391. var width = texture.width;
  14392. var faceDataArrays = callback(data);
  14393. if (!faceDataArrays) {
  14394. return;
  14395. }
  14396. if (mipmmapGenerator) {
  14397. var textureType = _this._getWebGLTextureType(type);
  14398. var internalFormat = _this._getInternalFormat(format);
  14399. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14400. var needConversion = false;
  14401. if (internalFormat === gl.RGB) {
  14402. internalFormat = gl.RGBA;
  14403. needConversion = true;
  14404. }
  14405. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14406. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14407. var mipData = mipmmapGenerator(faceDataArrays);
  14408. for (var level = 0; level < mipData.length; level++) {
  14409. var mipSize = width >> level;
  14410. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14411. var mipFaceData = mipData[level][faceIndex];
  14412. if (needConversion) {
  14413. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14414. }
  14415. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14416. }
  14417. }
  14418. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14419. }
  14420. else {
  14421. texture.generateMipMaps = !noMipmap;
  14422. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14423. }
  14424. texture.isReady = true;
  14425. // this.resetTextureCache();
  14426. scene._removePendingData(texture);
  14427. if (onLoad) {
  14428. onLoad();
  14429. }
  14430. };
  14431. this._loadFile(url, function (data) {
  14432. internalCallback(data);
  14433. }, undefined, scene.database, true, onerror);
  14434. return texture;
  14435. };
  14436. ;
  14437. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14438. if (compression === void 0) { compression = null; }
  14439. var internalFormat = this._getInternalFormat(format);
  14440. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14441. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14442. if (!this._doNotHandleContextLost) {
  14443. texture._bufferView = data;
  14444. texture.format = format;
  14445. texture.invertY = invertY;
  14446. texture._compression = compression;
  14447. }
  14448. if (texture.width % 4 !== 0) {
  14449. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14450. }
  14451. if (compression && data) {
  14452. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14453. }
  14454. else {
  14455. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14456. }
  14457. if (texture.generateMipMaps) {
  14458. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14459. }
  14460. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14461. // this.resetTextureCache();
  14462. texture.isReady = true;
  14463. };
  14464. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14465. if (compression === void 0) { compression = null; }
  14466. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14467. texture.baseWidth = width;
  14468. texture.baseHeight = height;
  14469. texture.baseDepth = depth;
  14470. texture.width = width;
  14471. texture.height = height;
  14472. texture.depth = depth;
  14473. texture.format = format;
  14474. texture.generateMipMaps = generateMipMaps;
  14475. texture.samplingMode = samplingMode;
  14476. texture.is3D = true;
  14477. if (!this._doNotHandleContextLost) {
  14478. texture._bufferView = data;
  14479. }
  14480. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14481. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14482. // Filters
  14483. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14484. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14485. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14486. if (generateMipMaps) {
  14487. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14488. }
  14489. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14490. this._internalTexturesCache.push(texture);
  14491. return texture;
  14492. };
  14493. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14494. var gl = this._gl;
  14495. if (!gl) {
  14496. return;
  14497. }
  14498. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14501. if (!noMipmap && !isCompressed) {
  14502. gl.generateMipmap(gl.TEXTURE_2D);
  14503. }
  14504. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14505. // this.resetTextureCache();
  14506. if (scene) {
  14507. scene._removePendingData(texture);
  14508. }
  14509. texture.onLoadedObservable.notifyObservers(texture);
  14510. texture.onLoadedObservable.clear();
  14511. };
  14512. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14513. var _this = this;
  14514. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14515. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14516. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14517. var gl = this._gl;
  14518. if (!gl) {
  14519. return;
  14520. }
  14521. if (!texture._webGLTexture) {
  14522. // this.resetTextureCache();
  14523. if (scene) {
  14524. scene._removePendingData(texture);
  14525. }
  14526. return;
  14527. }
  14528. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14529. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14530. texture.baseWidth = width;
  14531. texture.baseHeight = height;
  14532. texture.width = potWidth;
  14533. texture.height = potHeight;
  14534. texture.isReady = true;
  14535. if (processFunction(potWidth, potHeight, function () {
  14536. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14537. })) {
  14538. // Returning as texture needs extra async steps
  14539. return;
  14540. }
  14541. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14542. };
  14543. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14544. // Create new RGBA data container.
  14545. var rgbaData;
  14546. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14547. rgbaData = new Float32Array(width * height * 4);
  14548. }
  14549. else {
  14550. rgbaData = new Uint32Array(width * height * 4);
  14551. }
  14552. // Convert each pixel.
  14553. for (var x = 0; x < width; x++) {
  14554. for (var y = 0; y < height; y++) {
  14555. var index = (y * width + x) * 3;
  14556. var newIndex = (y * width + x) * 4;
  14557. // Map Old Value to new value.
  14558. rgbaData[newIndex + 0] = rgbData[index + 0];
  14559. rgbaData[newIndex + 1] = rgbData[index + 1];
  14560. rgbaData[newIndex + 2] = rgbData[index + 2];
  14561. // Add fully opaque alpha channel.
  14562. rgbaData[newIndex + 3] = 1;
  14563. }
  14564. }
  14565. return rgbaData;
  14566. };
  14567. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14568. var gl = this._gl;
  14569. if (texture._framebuffer) {
  14570. gl.deleteFramebuffer(texture._framebuffer);
  14571. texture._framebuffer = null;
  14572. }
  14573. if (texture._depthStencilBuffer) {
  14574. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14575. texture._depthStencilBuffer = null;
  14576. }
  14577. if (texture._MSAAFramebuffer) {
  14578. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14579. texture._MSAAFramebuffer = null;
  14580. }
  14581. if (texture._MSAARenderBuffer) {
  14582. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14583. texture._MSAARenderBuffer = null;
  14584. }
  14585. };
  14586. Engine.prototype._releaseTexture = function (texture) {
  14587. var gl = this._gl;
  14588. this._releaseFramebufferObjects(texture);
  14589. gl.deleteTexture(texture._webGLTexture);
  14590. // Unbind channels
  14591. this.unbindAllTextures();
  14592. var index = this._internalTexturesCache.indexOf(texture);
  14593. if (index !== -1) {
  14594. this._internalTexturesCache.splice(index, 1);
  14595. }
  14596. // Integrated fixed lod samplers.
  14597. if (texture._lodTextureHigh) {
  14598. texture._lodTextureHigh.dispose();
  14599. }
  14600. if (texture._lodTextureMid) {
  14601. texture._lodTextureMid.dispose();
  14602. }
  14603. if (texture._lodTextureLow) {
  14604. texture._lodTextureLow.dispose();
  14605. }
  14606. // Set output texture of post process to null if the texture has been released/disposed
  14607. this.scenes.forEach(function (scene) {
  14608. scene.postProcesses.forEach(function (postProcess) {
  14609. if (postProcess._outputTexture == texture) {
  14610. postProcess._outputTexture = null;
  14611. }
  14612. });
  14613. scene.cameras.forEach(function (camera) {
  14614. camera._postProcesses.forEach(function (postProcess) {
  14615. if (postProcess) {
  14616. if (postProcess._outputTexture == texture) {
  14617. postProcess._outputTexture = null;
  14618. }
  14619. }
  14620. });
  14621. });
  14622. });
  14623. };
  14624. Engine.prototype.setProgram = function (program) {
  14625. if (this._currentProgram !== program) {
  14626. this._gl.useProgram(program);
  14627. this._currentProgram = program;
  14628. }
  14629. };
  14630. Engine.prototype.bindSamplers = function (effect) {
  14631. this.setProgram(effect.getProgram());
  14632. var samplers = effect.getSamplers();
  14633. for (var index = 0; index < samplers.length; index++) {
  14634. var uniform = effect.getUniform(samplers[index]);
  14635. if (uniform) {
  14636. this._boundUniforms[index] = uniform;
  14637. }
  14638. }
  14639. this._currentEffect = null;
  14640. };
  14641. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14642. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14643. return;
  14644. }
  14645. // Remove
  14646. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14647. // Bind last to it
  14648. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14649. // Bind to dummy
  14650. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14651. };
  14652. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14653. if (!internalTexture) {
  14654. return -1;
  14655. }
  14656. internalTexture._initialSlot = channel;
  14657. if (this.disableTextureBindingOptimization) {
  14658. if (channel !== internalTexture._designatedSlot) {
  14659. this._textureCollisions.addCount(1, false);
  14660. }
  14661. }
  14662. else {
  14663. if (channel !== internalTexture._designatedSlot) {
  14664. if (internalTexture._designatedSlot > -1) {
  14665. return internalTexture._designatedSlot;
  14666. }
  14667. else {
  14668. // No slot for this texture, let's pick a new one (if we find a free slot)
  14669. if (this._nextFreeTextureSlots.length) {
  14670. return this._nextFreeTextureSlots[0];
  14671. }
  14672. // We need to recycle the oldest bound texture, sorry.
  14673. this._textureCollisions.addCount(1, false);
  14674. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14675. }
  14676. }
  14677. }
  14678. return channel;
  14679. };
  14680. Engine.prototype._linkTrackers = function (previous, next) {
  14681. previous.next = next;
  14682. next.previous = previous;
  14683. };
  14684. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14685. var currentSlot = internalTexture._designatedSlot;
  14686. if (currentSlot === -1) {
  14687. return -1;
  14688. }
  14689. internalTexture._designatedSlot = -1;
  14690. if (this.disableTextureBindingOptimization) {
  14691. return -1;
  14692. }
  14693. // Remove from bound list
  14694. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14695. // Free the slot
  14696. this._boundTexturesCache[currentSlot] = null;
  14697. this._nextFreeTextureSlots.push(currentSlot);
  14698. return currentSlot;
  14699. };
  14700. Engine.prototype._activateCurrentTexture = function () {
  14701. if (this._currentTextureChannel !== this._activeChannel) {
  14702. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14703. this._currentTextureChannel = this._activeChannel;
  14704. }
  14705. };
  14706. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14707. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14708. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14709. this._activeChannel = texture._designatedSlot;
  14710. }
  14711. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14712. var isTextureForRendering = texture && texture._initialSlot > -1;
  14713. if (currentTextureBound !== texture) {
  14714. if (currentTextureBound) {
  14715. this._removeDesignatedSlot(currentTextureBound);
  14716. }
  14717. this._activateCurrentTexture();
  14718. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14719. this._boundTexturesCache[this._activeChannel] = texture;
  14720. if (texture) {
  14721. if (!this.disableTextureBindingOptimization) {
  14722. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14723. if (slotIndex > -1) {
  14724. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14725. }
  14726. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14727. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14728. }
  14729. texture._designatedSlot = this._activeChannel;
  14730. }
  14731. }
  14732. else if (forTextureDataUpdate) {
  14733. this._activateCurrentTexture();
  14734. }
  14735. if (isTextureForRendering && !forTextureDataUpdate) {
  14736. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14737. }
  14738. };
  14739. Engine.prototype._bindTexture = function (channel, texture) {
  14740. if (channel < 0) {
  14741. return;
  14742. }
  14743. if (texture) {
  14744. channel = this._getCorrectTextureChannel(channel, texture);
  14745. }
  14746. this._activeChannel = channel;
  14747. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14748. };
  14749. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14750. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14751. };
  14752. /**
  14753. * Binds the output of the passed in post process to the texture channel specified
  14754. * @param channel The channel the texture should be bound to
  14755. * @param postProcess The post process which's output should be bound
  14756. */
  14757. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14758. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14759. };
  14760. Engine.prototype.unbindAllTextures = function () {
  14761. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14762. this._activeChannel = channel;
  14763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14764. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14765. if (this.webGLVersion > 1) {
  14766. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14767. }
  14768. }
  14769. };
  14770. /**
  14771. * Sets a texture to the according uniform.
  14772. * @param channel The texture channel
  14773. * @param uniform The uniform to set
  14774. * @param texture The texture to apply
  14775. */
  14776. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14777. if (channel < 0) {
  14778. return;
  14779. }
  14780. if (uniform) {
  14781. this._boundUniforms[channel] = uniform;
  14782. }
  14783. this._setTexture(channel, texture);
  14784. };
  14785. /**
  14786. * Sets a depth stencil texture from a render target to the according uniform.
  14787. * @param channel The texture channel
  14788. * @param uniform The uniform to set
  14789. * @param texture The render target texture containing the depth stencil texture to apply
  14790. */
  14791. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14792. if (channel < 0) {
  14793. return;
  14794. }
  14795. if (uniform) {
  14796. this._boundUniforms[channel] = uniform;
  14797. }
  14798. if (!texture || !texture.depthStencilTexture) {
  14799. this._setTexture(channel, null);
  14800. }
  14801. else {
  14802. this._setTexture(channel, texture, false, true);
  14803. }
  14804. };
  14805. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14806. var uniform = this._boundUniforms[sourceSlot];
  14807. if (uniform._currentState === destination) {
  14808. return;
  14809. }
  14810. this._gl.uniform1i(uniform, destination);
  14811. uniform._currentState = destination;
  14812. };
  14813. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14814. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14815. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14816. // Not ready?
  14817. if (!texture) {
  14818. if (this._boundTexturesCache[channel] != null) {
  14819. this._activeChannel = channel;
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14821. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14822. if (this.webGLVersion > 1) {
  14823. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14824. }
  14825. }
  14826. return false;
  14827. }
  14828. // Video
  14829. if (texture.video) {
  14830. this._activeChannel = channel;
  14831. texture.update();
  14832. }
  14833. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14834. texture.delayLoad();
  14835. return false;
  14836. }
  14837. var internalTexture;
  14838. if (depthStencilTexture) {
  14839. internalTexture = texture.depthStencilTexture;
  14840. }
  14841. else if (texture.isReady()) {
  14842. internalTexture = texture.getInternalTexture();
  14843. }
  14844. else if (texture.isCube) {
  14845. internalTexture = this.emptyCubeTexture;
  14846. }
  14847. else if (texture.is3D) {
  14848. internalTexture = this.emptyTexture3D;
  14849. }
  14850. else {
  14851. internalTexture = this.emptyTexture;
  14852. }
  14853. if (!isPartOfTextureArray) {
  14854. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14855. }
  14856. if (this._boundTexturesCache[channel] === internalTexture) {
  14857. this._moveBoundTextureOnTop(internalTexture);
  14858. if (!isPartOfTextureArray) {
  14859. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14860. }
  14861. return false;
  14862. }
  14863. this._activeChannel = channel;
  14864. if (internalTexture && internalTexture.is3D) {
  14865. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14866. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14867. internalTexture._cachedWrapU = texture.wrapU;
  14868. switch (texture.wrapU) {
  14869. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14870. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14871. break;
  14872. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14873. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14874. break;
  14875. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14876. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14877. break;
  14878. }
  14879. }
  14880. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14881. internalTexture._cachedWrapV = texture.wrapV;
  14882. switch (texture.wrapV) {
  14883. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14884. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14885. break;
  14886. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14887. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14888. break;
  14889. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14890. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14891. break;
  14892. }
  14893. }
  14894. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14895. internalTexture._cachedWrapR = texture.wrapR;
  14896. switch (texture.wrapR) {
  14897. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14898. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14899. break;
  14900. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14901. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14902. break;
  14903. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14904. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14905. break;
  14906. }
  14907. }
  14908. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14909. }
  14910. else if (internalTexture && internalTexture.isCube) {
  14911. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14912. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14913. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14914. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14915. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14916. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14917. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14918. }
  14919. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14920. }
  14921. else {
  14922. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14923. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14924. internalTexture._cachedWrapU = texture.wrapU;
  14925. switch (texture.wrapU) {
  14926. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14927. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14928. break;
  14929. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14930. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14931. break;
  14932. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14933. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14934. break;
  14935. }
  14936. }
  14937. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14938. internalTexture._cachedWrapV = texture.wrapV;
  14939. switch (texture.wrapV) {
  14940. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14941. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14942. break;
  14943. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14944. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14945. break;
  14946. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14947. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14948. break;
  14949. }
  14950. }
  14951. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14952. }
  14953. return true;
  14954. };
  14955. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14956. if (channel < 0 || !uniform) {
  14957. return;
  14958. }
  14959. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14960. this._textureUnits = new Int32Array(textures.length);
  14961. }
  14962. for (var i = 0; i < textures.length; i++) {
  14963. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14964. }
  14965. this._gl.uniform1iv(uniform, this._textureUnits);
  14966. for (var index = 0; index < textures.length; index++) {
  14967. this._setTexture(this._textureUnits[index], textures[index], true);
  14968. }
  14969. };
  14970. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14971. var internalTexture = texture.getInternalTexture();
  14972. if (!internalTexture) {
  14973. return;
  14974. }
  14975. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14976. var value = texture.anisotropicFilteringLevel;
  14977. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14978. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14979. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14980. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14981. }
  14982. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14983. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14984. internalTexture._cachedAnisotropicFilteringLevel = value;
  14985. }
  14986. };
  14987. Engine.prototype.readPixels = function (x, y, width, height) {
  14988. var data = new Uint8Array(height * width * 4);
  14989. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14990. return data;
  14991. };
  14992. /**
  14993. * Add an externaly attached data from its key.
  14994. * This method call will fail and return false, if such key already exists.
  14995. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14996. * @param key the unique key that identifies the data
  14997. * @param data the data object to associate to the key for this Engine instance
  14998. * @return true if no such key were already present and the data was added successfully, false otherwise
  14999. */
  15000. Engine.prototype.addExternalData = function (key, data) {
  15001. if (!this._externalData) {
  15002. this._externalData = new BABYLON.StringDictionary();
  15003. }
  15004. return this._externalData.add(key, data);
  15005. };
  15006. /**
  15007. * Get an externaly attached data from its key
  15008. * @param key the unique key that identifies the data
  15009. * @return the associated data, if present (can be null), or undefined if not present
  15010. */
  15011. Engine.prototype.getExternalData = function (key) {
  15012. if (!this._externalData) {
  15013. this._externalData = new BABYLON.StringDictionary();
  15014. }
  15015. return this._externalData.get(key);
  15016. };
  15017. /**
  15018. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15019. * @param key the unique key that identifies the data
  15020. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15021. * @return the associated data, can be null if the factory returned null.
  15022. */
  15023. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15024. if (!this._externalData) {
  15025. this._externalData = new BABYLON.StringDictionary();
  15026. }
  15027. return this._externalData.getOrAddWithFactory(key, factory);
  15028. };
  15029. /**
  15030. * Remove an externaly attached data from the Engine instance
  15031. * @param key the unique key that identifies the data
  15032. * @return true if the data was successfully removed, false if it doesn't exist
  15033. */
  15034. Engine.prototype.removeExternalData = function (key) {
  15035. if (!this._externalData) {
  15036. this._externalData = new BABYLON.StringDictionary();
  15037. }
  15038. return this._externalData.remove(key);
  15039. };
  15040. Engine.prototype.unbindAllAttributes = function () {
  15041. if (this._mustWipeVertexAttributes) {
  15042. this._mustWipeVertexAttributes = false;
  15043. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15044. this._gl.disableVertexAttribArray(i);
  15045. this._vertexAttribArraysEnabled[i] = false;
  15046. this._currentBufferPointers[i].active = false;
  15047. }
  15048. return;
  15049. }
  15050. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15051. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15052. continue;
  15053. }
  15054. this._gl.disableVertexAttribArray(i);
  15055. this._vertexAttribArraysEnabled[i] = false;
  15056. this._currentBufferPointers[i].active = false;
  15057. }
  15058. };
  15059. Engine.prototype.releaseEffects = function () {
  15060. for (var name in this._compiledEffects) {
  15061. this._deleteProgram(this._compiledEffects[name]._program);
  15062. }
  15063. this._compiledEffects = {};
  15064. };
  15065. // Dispose
  15066. Engine.prototype.dispose = function () {
  15067. this.hideLoadingUI();
  15068. this.stopRenderLoop();
  15069. // Release postProcesses
  15070. while (this.postProcesses.length) {
  15071. this.postProcesses[0].dispose();
  15072. }
  15073. // Empty texture
  15074. if (this._emptyTexture) {
  15075. this._releaseTexture(this._emptyTexture);
  15076. this._emptyTexture = null;
  15077. }
  15078. if (this._emptyCubeTexture) {
  15079. this._releaseTexture(this._emptyCubeTexture);
  15080. this._emptyCubeTexture = null;
  15081. }
  15082. // Rescale PP
  15083. if (this._rescalePostProcess) {
  15084. this._rescalePostProcess.dispose();
  15085. }
  15086. // Release scenes
  15087. while (this.scenes.length) {
  15088. this.scenes[0].dispose();
  15089. }
  15090. // Release audio engine
  15091. if (Engine.audioEngine) {
  15092. Engine.audioEngine.dispose();
  15093. }
  15094. // Release effects
  15095. this.releaseEffects();
  15096. // Unbind
  15097. this.unbindAllAttributes();
  15098. this._boundUniforms = [];
  15099. if (this._dummyFramebuffer) {
  15100. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15101. }
  15102. //WebVR
  15103. this.disableVR();
  15104. // Events
  15105. if (BABYLON.Tools.IsWindowObjectExist()) {
  15106. window.removeEventListener("blur", this._onBlur);
  15107. window.removeEventListener("focus", this._onFocus);
  15108. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15109. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15110. if (this._renderingCanvas) {
  15111. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15112. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15113. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15114. if (!this._doNotHandleContextLost) {
  15115. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15116. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15117. }
  15118. }
  15119. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15120. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15121. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15122. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15123. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15124. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15125. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15126. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15127. if (this._onVrDisplayConnect) {
  15128. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15129. if (this._onVrDisplayDisconnect) {
  15130. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15131. }
  15132. if (this._onVrDisplayPresentChange) {
  15133. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15134. }
  15135. this._onVrDisplayConnect = null;
  15136. this._onVrDisplayDisconnect = null;
  15137. }
  15138. }
  15139. // Remove from Instances
  15140. var index = Engine.Instances.indexOf(this);
  15141. if (index >= 0) {
  15142. Engine.Instances.splice(index, 1);
  15143. }
  15144. this._workingCanvas = null;
  15145. this._workingContext = null;
  15146. this._currentBufferPointers = [];
  15147. this._renderingCanvas = null;
  15148. this._currentProgram = null;
  15149. this._bindedRenderFunction = null;
  15150. this.onResizeObservable.clear();
  15151. this.onCanvasBlurObservable.clear();
  15152. this.onCanvasFocusObservable.clear();
  15153. this.onCanvasPointerOutObservable.clear();
  15154. this.onBeginFrameObservable.clear();
  15155. this.onEndFrameObservable.clear();
  15156. BABYLON.Effect.ResetCache();
  15157. // Abort active requests
  15158. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15159. var request = _a[_i];
  15160. request.abort();
  15161. }
  15162. };
  15163. // Loading screen
  15164. Engine.prototype.displayLoadingUI = function () {
  15165. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15166. return;
  15167. }
  15168. var loadingScreen = this.loadingScreen;
  15169. if (loadingScreen) {
  15170. loadingScreen.displayLoadingUI();
  15171. }
  15172. };
  15173. Engine.prototype.hideLoadingUI = function () {
  15174. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15175. return;
  15176. }
  15177. var loadingScreen = this.loadingScreen;
  15178. if (loadingScreen) {
  15179. loadingScreen.hideLoadingUI();
  15180. }
  15181. };
  15182. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15183. get: function () {
  15184. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15185. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15186. return this._loadingScreen;
  15187. },
  15188. set: function (loadingScreen) {
  15189. this._loadingScreen = loadingScreen;
  15190. },
  15191. enumerable: true,
  15192. configurable: true
  15193. });
  15194. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15195. set: function (text) {
  15196. this.loadingScreen.loadingUIText = text;
  15197. },
  15198. enumerable: true,
  15199. configurable: true
  15200. });
  15201. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15202. set: function (color) {
  15203. this.loadingScreen.loadingUIBackgroundColor = color;
  15204. },
  15205. enumerable: true,
  15206. configurable: true
  15207. });
  15208. Engine.prototype.attachContextLostEvent = function (callback) {
  15209. if (this._renderingCanvas) {
  15210. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15211. }
  15212. };
  15213. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15214. if (this._renderingCanvas) {
  15215. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15216. }
  15217. };
  15218. Engine.prototype.getVertexShaderSource = function (program) {
  15219. var shaders = this._gl.getAttachedShaders(program);
  15220. if (!shaders) {
  15221. return null;
  15222. }
  15223. return this._gl.getShaderSource(shaders[0]);
  15224. };
  15225. Engine.prototype.getFragmentShaderSource = function (program) {
  15226. var shaders = this._gl.getAttachedShaders(program);
  15227. if (!shaders) {
  15228. return null;
  15229. }
  15230. return this._gl.getShaderSource(shaders[1]);
  15231. };
  15232. Engine.prototype.getError = function () {
  15233. return this._gl.getError();
  15234. };
  15235. // FPS
  15236. Engine.prototype.getFps = function () {
  15237. return this._fps;
  15238. };
  15239. Engine.prototype.getDeltaTime = function () {
  15240. return this._deltaTime;
  15241. };
  15242. Engine.prototype._measureFps = function () {
  15243. this._performanceMonitor.sampleFrame();
  15244. this._fps = this._performanceMonitor.averageFPS;
  15245. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15246. };
  15247. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15248. if (faceIndex === void 0) { faceIndex = -1; }
  15249. var gl = this._gl;
  15250. if (!this._dummyFramebuffer) {
  15251. var dummy = gl.createFramebuffer();
  15252. if (!dummy) {
  15253. throw new Error("Unable to create dummy framebuffer");
  15254. }
  15255. this._dummyFramebuffer = dummy;
  15256. }
  15257. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15258. if (faceIndex > -1) {
  15259. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15260. }
  15261. else {
  15262. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15263. }
  15264. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15265. var buffer;
  15266. switch (readType) {
  15267. case gl.UNSIGNED_BYTE:
  15268. buffer = new Uint8Array(4 * width * height);
  15269. readType = gl.UNSIGNED_BYTE;
  15270. break;
  15271. default:
  15272. buffer = new Float32Array(4 * width * height);
  15273. readType = gl.FLOAT;
  15274. break;
  15275. }
  15276. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15277. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15278. return buffer;
  15279. };
  15280. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15281. if (this._webGLVersion > 1) {
  15282. return this._caps.colorBufferFloat;
  15283. }
  15284. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15285. };
  15286. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15287. if (this._webGLVersion > 1) {
  15288. return this._caps.colorBufferFloat;
  15289. }
  15290. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15291. };
  15292. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15293. Engine.prototype._canRenderToFramebuffer = function (type) {
  15294. var gl = this._gl;
  15295. //clear existing errors
  15296. while (gl.getError() !== gl.NO_ERROR) { }
  15297. var successful = true;
  15298. var texture = gl.createTexture();
  15299. gl.bindTexture(gl.TEXTURE_2D, texture);
  15300. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15302. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15303. var fb = gl.createFramebuffer();
  15304. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15305. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15306. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15307. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15308. successful = successful && (gl.getError() === gl.NO_ERROR);
  15309. //try render by clearing frame buffer's color buffer
  15310. if (successful) {
  15311. gl.clear(gl.COLOR_BUFFER_BIT);
  15312. successful = successful && (gl.getError() === gl.NO_ERROR);
  15313. }
  15314. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15315. if (successful) {
  15316. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15317. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15318. var readFormat = gl.RGBA;
  15319. var readType = gl.UNSIGNED_BYTE;
  15320. var buffer = new Uint8Array(4);
  15321. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15322. successful = successful && (gl.getError() === gl.NO_ERROR);
  15323. }
  15324. //clean up
  15325. gl.deleteTexture(texture);
  15326. gl.deleteFramebuffer(fb);
  15327. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15328. //clear accumulated errors
  15329. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15330. return successful;
  15331. };
  15332. Engine.prototype._getWebGLTextureType = function (type) {
  15333. if (type === Engine.TEXTURETYPE_FLOAT) {
  15334. return this._gl.FLOAT;
  15335. }
  15336. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15337. // Add Half Float Constant.
  15338. return this._gl.HALF_FLOAT_OES;
  15339. }
  15340. return this._gl.UNSIGNED_BYTE;
  15341. };
  15342. ;
  15343. Engine.prototype._getInternalFormat = function (format) {
  15344. var internalFormat = this._gl.RGBA;
  15345. switch (format) {
  15346. case Engine.TEXTUREFORMAT_ALPHA:
  15347. internalFormat = this._gl.ALPHA;
  15348. break;
  15349. case Engine.TEXTUREFORMAT_LUMINANCE:
  15350. internalFormat = this._gl.LUMINANCE;
  15351. break;
  15352. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15353. internalFormat = this._gl.LUMINANCE_ALPHA;
  15354. break;
  15355. case Engine.TEXTUREFORMAT_RGB:
  15356. case Engine.TEXTUREFORMAT_RGB32F:
  15357. internalFormat = this._gl.RGB;
  15358. break;
  15359. case Engine.TEXTUREFORMAT_RGBA:
  15360. case Engine.TEXTUREFORMAT_RGBA32F:
  15361. internalFormat = this._gl.RGBA;
  15362. break;
  15363. case Engine.TEXTUREFORMAT_R32F:
  15364. internalFormat = this._gl.RED;
  15365. break;
  15366. case Engine.TEXTUREFORMAT_RG32F:
  15367. internalFormat = this._gl.RG;
  15368. break;
  15369. }
  15370. return internalFormat;
  15371. };
  15372. /** @ignore */
  15373. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15374. if (this._webGLVersion === 1) {
  15375. if (format) {
  15376. switch (format) {
  15377. case Engine.TEXTUREFORMAT_LUMINANCE:
  15378. return this._gl.LUMINANCE;
  15379. }
  15380. }
  15381. return this._gl.RGBA;
  15382. }
  15383. if (type === Engine.TEXTURETYPE_FLOAT) {
  15384. if (format) {
  15385. switch (format) {
  15386. case Engine.TEXTUREFORMAT_R32F:
  15387. return this._gl.R32F;
  15388. case Engine.TEXTUREFORMAT_RG32F:
  15389. return this._gl.RG32F;
  15390. case Engine.TEXTUREFORMAT_RGB32F:
  15391. return this._gl.RGB32F;
  15392. }
  15393. }
  15394. return this._gl.RGBA32F;
  15395. }
  15396. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15397. return this._gl.RGBA16F;
  15398. }
  15399. if (format) {
  15400. switch (format) {
  15401. case Engine.TEXTUREFORMAT_LUMINANCE:
  15402. return this._gl.LUMINANCE;
  15403. }
  15404. }
  15405. return this._gl.RGBA;
  15406. };
  15407. ;
  15408. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15409. if (type === Engine.TEXTURETYPE_FLOAT) {
  15410. return this._gl.RGBA32F;
  15411. }
  15412. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15413. return this._gl.RGBA16F;
  15414. }
  15415. return this._gl.RGBA8;
  15416. };
  15417. ;
  15418. Engine.prototype.createQuery = function () {
  15419. return this._gl.createQuery();
  15420. };
  15421. Engine.prototype.deleteQuery = function (query) {
  15422. this._gl.deleteQuery(query);
  15423. return this;
  15424. };
  15425. Engine.prototype.isQueryResultAvailable = function (query) {
  15426. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15427. };
  15428. Engine.prototype.getQueryResult = function (query) {
  15429. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15430. };
  15431. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15432. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15433. this._gl.beginQuery(glAlgorithm, query);
  15434. return this;
  15435. };
  15436. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15437. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15438. this._gl.endQuery(glAlgorithm);
  15439. return this;
  15440. };
  15441. /* Time queries */
  15442. Engine.prototype._createTimeQuery = function () {
  15443. var timerQuery = this._caps.timerQuery;
  15444. if (timerQuery.createQueryEXT) {
  15445. return timerQuery.createQueryEXT();
  15446. }
  15447. return this.createQuery();
  15448. };
  15449. Engine.prototype._deleteTimeQuery = function (query) {
  15450. var timerQuery = this._caps.timerQuery;
  15451. if (timerQuery.deleteQueryEXT) {
  15452. timerQuery.deleteQueryEXT(query);
  15453. return;
  15454. }
  15455. this.deleteQuery(query);
  15456. };
  15457. Engine.prototype._getTimeQueryResult = function (query) {
  15458. var timerQuery = this._caps.timerQuery;
  15459. if (timerQuery.getQueryObjectEXT) {
  15460. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15461. }
  15462. return this.getQueryResult(query);
  15463. };
  15464. Engine.prototype._getTimeQueryAvailability = function (query) {
  15465. var timerQuery = this._caps.timerQuery;
  15466. if (timerQuery.getQueryObjectEXT) {
  15467. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15468. }
  15469. return this.isQueryResultAvailable(query);
  15470. };
  15471. Engine.prototype.startTimeQuery = function () {
  15472. var timerQuery = this._caps.timerQuery;
  15473. if (!timerQuery) {
  15474. return null;
  15475. }
  15476. var token = new BABYLON._TimeToken();
  15477. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15478. if (this._caps.canUseTimestampForTimerQuery) {
  15479. token._startTimeQuery = this._createTimeQuery();
  15480. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15481. }
  15482. else {
  15483. if (this._currentNonTimestampToken) {
  15484. return this._currentNonTimestampToken;
  15485. }
  15486. token._timeElapsedQuery = this._createTimeQuery();
  15487. if (timerQuery.beginQueryEXT) {
  15488. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15489. }
  15490. else {
  15491. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15492. }
  15493. this._currentNonTimestampToken = token;
  15494. }
  15495. return token;
  15496. };
  15497. Engine.prototype.endTimeQuery = function (token) {
  15498. var timerQuery = this._caps.timerQuery;
  15499. if (!timerQuery || !token) {
  15500. return -1;
  15501. }
  15502. if (this._caps.canUseTimestampForTimerQuery) {
  15503. if (!token._startTimeQuery) {
  15504. return -1;
  15505. }
  15506. if (!token._endTimeQuery) {
  15507. token._endTimeQuery = this._createTimeQuery();
  15508. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15509. }
  15510. }
  15511. else if (!token._timeElapsedQueryEnded) {
  15512. if (!token._timeElapsedQuery) {
  15513. return -1;
  15514. }
  15515. if (timerQuery.endQueryEXT) {
  15516. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15517. }
  15518. else {
  15519. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15520. }
  15521. token._timeElapsedQueryEnded = true;
  15522. }
  15523. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15524. var available = false;
  15525. if (token._endTimeQuery) {
  15526. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15527. }
  15528. else if (token._timeElapsedQuery) {
  15529. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15530. }
  15531. if (available && !disjoint) {
  15532. var result = 0;
  15533. if (this._caps.canUseTimestampForTimerQuery) {
  15534. if (!token._startTimeQuery || !token._endTimeQuery) {
  15535. return -1;
  15536. }
  15537. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15538. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15539. result = timeEnd - timeStart;
  15540. this._deleteTimeQuery(token._startTimeQuery);
  15541. this._deleteTimeQuery(token._endTimeQuery);
  15542. token._startTimeQuery = null;
  15543. token._endTimeQuery = null;
  15544. }
  15545. else {
  15546. if (!token._timeElapsedQuery) {
  15547. return -1;
  15548. }
  15549. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15550. this._deleteTimeQuery(token._timeElapsedQuery);
  15551. token._timeElapsedQuery = null;
  15552. token._timeElapsedQueryEnded = false;
  15553. this._currentNonTimestampToken = null;
  15554. }
  15555. return result;
  15556. }
  15557. return -1;
  15558. };
  15559. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15560. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15561. };
  15562. // Transform feedback
  15563. Engine.prototype.createTransformFeedback = function () {
  15564. return this._gl.createTransformFeedback();
  15565. };
  15566. Engine.prototype.deleteTransformFeedback = function (value) {
  15567. this._gl.deleteTransformFeedback(value);
  15568. };
  15569. Engine.prototype.bindTransformFeedback = function (value) {
  15570. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15571. };
  15572. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15573. if (usePoints === void 0) { usePoints = true; }
  15574. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15575. };
  15576. Engine.prototype.endTransformFeedback = function () {
  15577. this._gl.endTransformFeedback();
  15578. };
  15579. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15580. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15581. };
  15582. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15583. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15584. };
  15585. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15586. var _this = this;
  15587. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15588. this._activeRequests.push(request);
  15589. request.onCompleteObservable.add(function (request) {
  15590. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15591. });
  15592. return request;
  15593. };
  15594. /** @ignore */
  15595. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15596. var _this = this;
  15597. return new Promise(function (resolve, reject) {
  15598. _this._loadFile(url, function (data) {
  15599. resolve(data);
  15600. }, undefined, database, useArrayBuffer, function (request, exception) {
  15601. reject(exception);
  15602. });
  15603. });
  15604. };
  15605. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15606. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15607. var onload = function (data) {
  15608. loadedFiles[index] = data;
  15609. loadedFiles._internalCount++;
  15610. if (loadedFiles._internalCount === 6) {
  15611. onfinish(loadedFiles);
  15612. }
  15613. };
  15614. var onerror = function (request, exception) {
  15615. if (onErrorCallBack && request) {
  15616. onErrorCallBack(request.status + " " + request.statusText, exception);
  15617. }
  15618. };
  15619. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15620. };
  15621. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15622. if (onError === void 0) { onError = null; }
  15623. var loadedFiles = [];
  15624. loadedFiles._internalCount = 0;
  15625. for (var index = 0; index < 6; index++) {
  15626. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15627. }
  15628. };
  15629. // Statics
  15630. Engine.isSupported = function () {
  15631. try {
  15632. var tempcanvas = document.createElement("canvas");
  15633. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15634. return gl != null && !!window.WebGLRenderingContext;
  15635. }
  15636. catch (e) {
  15637. return false;
  15638. }
  15639. };
  15640. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15641. Engine.ExceptionList = [
  15642. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15643. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15644. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15645. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15646. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15647. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15648. ];
  15649. Engine.Instances = new Array();
  15650. // Const statics
  15651. Engine._ALPHA_DISABLE = 0;
  15652. Engine._ALPHA_ADD = 1;
  15653. Engine._ALPHA_COMBINE = 2;
  15654. Engine._ALPHA_SUBTRACT = 3;
  15655. Engine._ALPHA_MULTIPLY = 4;
  15656. Engine._ALPHA_MAXIMIZED = 5;
  15657. Engine._ALPHA_ONEONE = 6;
  15658. Engine._ALPHA_PREMULTIPLIED = 7;
  15659. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15660. Engine._ALPHA_INTERPOLATE = 9;
  15661. Engine._ALPHA_SCREENMODE = 10;
  15662. Engine._DELAYLOADSTATE_NONE = 0;
  15663. Engine._DELAYLOADSTATE_LOADED = 1;
  15664. Engine._DELAYLOADSTATE_LOADING = 2;
  15665. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15666. Engine._TEXTUREFORMAT_ALPHA = 0;
  15667. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15668. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15669. Engine._TEXTUREFORMAT_RGB = 4;
  15670. Engine._TEXTUREFORMAT_RGBA = 5;
  15671. Engine._TEXTUREFORMAT_R32F = 6;
  15672. Engine._TEXTUREFORMAT_RG32F = 7;
  15673. Engine._TEXTUREFORMAT_RGB32F = 8;
  15674. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15675. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15676. Engine._TEXTURETYPE_FLOAT = 1;
  15677. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15678. // Depht or Stencil test Constants.
  15679. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15680. 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.
  15681. 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.
  15682. 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.
  15683. 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.
  15684. 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.
  15685. 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.
  15686. 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.
  15687. // Stencil Actions Constants.
  15688. Engine._KEEP = 0x1E00;
  15689. Engine._REPLACE = 0x1E01;
  15690. Engine._INCR = 0x1E02;
  15691. Engine._DECR = 0x1E03;
  15692. Engine._INVERT = 0x150A;
  15693. Engine._INCR_WRAP = 0x8507;
  15694. Engine._DECR_WRAP = 0x8508;
  15695. // Texture rescaling mode
  15696. Engine._SCALEMODE_FLOOR = 1;
  15697. Engine._SCALEMODE_NEAREST = 2;
  15698. Engine._SCALEMODE_CEILING = 3;
  15699. // Updatable statics so stick with vars here
  15700. Engine.CollisionsEpsilon = 0.001;
  15701. Engine.CodeRepository = "src/";
  15702. Engine.ShadersRepository = "src/Shaders/";
  15703. return Engine;
  15704. }());
  15705. BABYLON.Engine = Engine;
  15706. })(BABYLON || (BABYLON = {}));
  15707. //# sourceMappingURL=babylon.engine.js.map
  15708. "use strict";
  15709. var BABYLON;
  15710. (function (BABYLON) {
  15711. /**
  15712. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15713. */
  15714. var Node = /** @class */ (function () {
  15715. /**
  15716. * Creates a new Node
  15717. * @param {string} name - the name and id to be given to this node
  15718. * @param {BABYLON.Scene} the scene this node will be added to
  15719. */
  15720. function Node(name, scene) {
  15721. if (scene === void 0) { scene = null; }
  15722. /**
  15723. * Gets or sets a string used to store user defined state for the node
  15724. */
  15725. this.state = "";
  15726. /**
  15727. * Gets or sets an object used to store user defined information for the node
  15728. */
  15729. this.metadata = null;
  15730. /**
  15731. * Gets or sets a boolean used to define if the node must be serialized
  15732. */
  15733. this.doNotSerialize = false;
  15734. /** @ignore */
  15735. this._isDisposed = false;
  15736. /**
  15737. * Gets a list of {BABYLON.Animation} associated with the node
  15738. */
  15739. this.animations = new Array();
  15740. this._ranges = {};
  15741. this._isEnabled = true;
  15742. this._isReady = true;
  15743. /** @ignore */
  15744. this._currentRenderId = -1;
  15745. this._parentRenderId = -1;
  15746. this._childRenderId = -1;
  15747. this._animationPropertiesOverride = null;
  15748. /**
  15749. * An event triggered when the mesh is disposed
  15750. * @type {BABYLON.Observable}
  15751. */
  15752. this.onDisposeObservable = new BABYLON.Observable();
  15753. // Behaviors
  15754. this._behaviors = new Array();
  15755. this.name = name;
  15756. this.id = name;
  15757. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15758. this.uniqueId = this._scene.getUniqueId();
  15759. this._initCache();
  15760. }
  15761. /**
  15762. * Gets a boolean indicating if the node has been disposed
  15763. * @returns true if the node was disposed
  15764. */
  15765. Node.prototype.isDisposed = function () {
  15766. return this._isDisposed;
  15767. };
  15768. Object.defineProperty(Node.prototype, "parent", {
  15769. get: function () {
  15770. return this._parentNode;
  15771. },
  15772. /**
  15773. * Gets or sets the parent of the node
  15774. */
  15775. set: function (parent) {
  15776. if (this._parentNode === parent) {
  15777. return;
  15778. }
  15779. // Remove self from list of children of parent
  15780. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15781. var index = this._parentNode._children.indexOf(this);
  15782. if (index !== -1) {
  15783. this._parentNode._children.splice(index, 1);
  15784. }
  15785. }
  15786. // Store new parent
  15787. this._parentNode = parent;
  15788. // Add as child to new parent
  15789. if (this._parentNode) {
  15790. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15791. this._parentNode._children = new Array();
  15792. }
  15793. this._parentNode._children.push(this);
  15794. }
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15800. /**
  15801. * Gets or sets the animation properties override
  15802. */
  15803. get: function () {
  15804. return this._animationPropertiesOverride;
  15805. },
  15806. set: function (value) {
  15807. this._animationPropertiesOverride = value;
  15808. },
  15809. enumerable: true,
  15810. configurable: true
  15811. });
  15812. /**
  15813. * Gets a string idenfifying the name of the class
  15814. * @returns "Node" string
  15815. */
  15816. Node.prototype.getClassName = function () {
  15817. return "Node";
  15818. };
  15819. Object.defineProperty(Node.prototype, "onDispose", {
  15820. /**
  15821. * Sets a callback that will be raised when the node will be disposed
  15822. */
  15823. set: function (callback) {
  15824. if (this._onDisposeObserver) {
  15825. this.onDisposeObservable.remove(this._onDisposeObserver);
  15826. }
  15827. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15828. },
  15829. enumerable: true,
  15830. configurable: true
  15831. });
  15832. /**
  15833. * Gets the scene of the node
  15834. * @returns a {BABYLON.Scene}
  15835. */
  15836. Node.prototype.getScene = function () {
  15837. return this._scene;
  15838. };
  15839. /**
  15840. * Gets the engine of the node
  15841. * @returns a {BABYLON.Engine}
  15842. */
  15843. Node.prototype.getEngine = function () {
  15844. return this._scene.getEngine();
  15845. };
  15846. /**
  15847. * Attach a behavior to the node
  15848. * @see http://doc.babylonjs.com/features/behaviour
  15849. * @param behavior defines the behavior to attach
  15850. * @returns the current Node
  15851. */
  15852. Node.prototype.addBehavior = function (behavior) {
  15853. var _this = this;
  15854. var index = this._behaviors.indexOf(behavior);
  15855. if (index !== -1) {
  15856. return this;
  15857. }
  15858. behavior.init();
  15859. if (this._scene.isLoading) {
  15860. // We defer the attach when the scene will be loaded
  15861. var observer = this._scene.onDataLoadedObservable.add(function () {
  15862. behavior.attach(_this);
  15863. setTimeout(function () {
  15864. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15865. _this._scene.onDataLoadedObservable.remove(observer);
  15866. }, 0);
  15867. });
  15868. }
  15869. else {
  15870. behavior.attach(this);
  15871. }
  15872. this._behaviors.push(behavior);
  15873. return this;
  15874. };
  15875. /**
  15876. * Remove an attached behavior
  15877. * @see http://doc.babylonjs.com/features/behaviour
  15878. * @param behavior defines the behavior to attach
  15879. * @returns the current Node
  15880. */
  15881. Node.prototype.removeBehavior = function (behavior) {
  15882. var index = this._behaviors.indexOf(behavior);
  15883. if (index === -1) {
  15884. return this;
  15885. }
  15886. this._behaviors[index].detach();
  15887. this._behaviors.splice(index, 1);
  15888. return this;
  15889. };
  15890. Object.defineProperty(Node.prototype, "behaviors", {
  15891. /**
  15892. * Gets the list of attached behaviors
  15893. * @see http://doc.babylonjs.com/features/behaviour
  15894. */
  15895. get: function () {
  15896. return this._behaviors;
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. /**
  15902. * Gets an attached behavior by name
  15903. * @param name defines the name of the behavior to look for
  15904. * @see http://doc.babylonjs.com/features/behaviour
  15905. * @returns null if behavior was not found else the requested behavior
  15906. */
  15907. Node.prototype.getBehaviorByName = function (name) {
  15908. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15909. var behavior = _a[_i];
  15910. if (behavior.name === name) {
  15911. return behavior;
  15912. }
  15913. }
  15914. return null;
  15915. };
  15916. /**
  15917. * Returns the world matrix of the node
  15918. * @returns a matrix containing the node's world matrix
  15919. */
  15920. Node.prototype.getWorldMatrix = function () {
  15921. return BABYLON.Matrix.Identity();
  15922. };
  15923. // override it in derived class if you add new variables to the cache
  15924. // and call the parent class method
  15925. /** @ignore */
  15926. Node.prototype._initCache = function () {
  15927. this._cache = {};
  15928. this._cache.parent = undefined;
  15929. };
  15930. /** @ignore */
  15931. Node.prototype.updateCache = function (force) {
  15932. if (!force && this.isSynchronized())
  15933. return;
  15934. this._cache.parent = this.parent;
  15935. this._updateCache();
  15936. };
  15937. // override it in derived class if you add new variables to the cache
  15938. // and call the parent class method if !ignoreParentClass
  15939. /** @ignore */
  15940. Node.prototype._updateCache = function (ignoreParentClass) {
  15941. };
  15942. // override it in derived class if you add new variables to the cache
  15943. /** @ignore */
  15944. Node.prototype._isSynchronized = function () {
  15945. return true;
  15946. };
  15947. /** @ignore */
  15948. Node.prototype._markSyncedWithParent = function () {
  15949. if (this.parent) {
  15950. this._parentRenderId = this.parent._childRenderId;
  15951. }
  15952. };
  15953. /** @ignore */
  15954. Node.prototype.isSynchronizedWithParent = function () {
  15955. if (!this.parent) {
  15956. return true;
  15957. }
  15958. if (this._parentRenderId !== this.parent._childRenderId) {
  15959. return false;
  15960. }
  15961. return this.parent.isSynchronized();
  15962. };
  15963. /** @ignore */
  15964. Node.prototype.isSynchronized = function (updateCache) {
  15965. var check = this.hasNewParent();
  15966. check = check || !this.isSynchronizedWithParent();
  15967. check = check || !this._isSynchronized();
  15968. if (updateCache)
  15969. this.updateCache(true);
  15970. return !check;
  15971. };
  15972. /** @ignore */
  15973. Node.prototype.hasNewParent = function (update) {
  15974. if (this._cache.parent === this.parent)
  15975. return false;
  15976. if (update)
  15977. this._cache.parent = this.parent;
  15978. return true;
  15979. };
  15980. /**
  15981. * Is this node ready to be used/rendered
  15982. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15983. * @return true if the node is ready
  15984. */
  15985. Node.prototype.isReady = function (completeCheck) {
  15986. if (completeCheck === void 0) { completeCheck = false; }
  15987. return this._isReady;
  15988. };
  15989. /**
  15990. * Is this node enabled?
  15991. * 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
  15992. * @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
  15993. * @return whether this node (and its parent) is enabled
  15994. */
  15995. Node.prototype.isEnabled = function (checkAncestors) {
  15996. if (checkAncestors === void 0) { checkAncestors = true; }
  15997. if (checkAncestors === false) {
  15998. return this._isEnabled;
  15999. }
  16000. if (this._isEnabled === false) {
  16001. return false;
  16002. }
  16003. if (this.parent !== undefined && this.parent !== null) {
  16004. return this.parent.isEnabled(checkAncestors);
  16005. }
  16006. return true;
  16007. };
  16008. /**
  16009. * Set the enabled state of this node
  16010. * @param value defines the new enabled state
  16011. */
  16012. Node.prototype.setEnabled = function (value) {
  16013. this._isEnabled = value;
  16014. };
  16015. /**
  16016. * Is this node a descendant of the given node?
  16017. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  16018. * @param ancestor defines the parent node to inspect
  16019. * @returns a boolean indicating if this node is a descendant of the given node
  16020. */
  16021. Node.prototype.isDescendantOf = function (ancestor) {
  16022. if (this.parent) {
  16023. if (this.parent === ancestor) {
  16024. return true;
  16025. }
  16026. return this.parent.isDescendantOf(ancestor);
  16027. }
  16028. return false;
  16029. };
  16030. /** @ignore */
  16031. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16032. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16033. if (!this._children) {
  16034. return;
  16035. }
  16036. for (var index = 0; index < this._children.length; index++) {
  16037. var item = this._children[index];
  16038. if (!predicate || predicate(item)) {
  16039. results.push(item);
  16040. }
  16041. if (!directDescendantsOnly) {
  16042. item._getDescendants(results, false, predicate);
  16043. }
  16044. }
  16045. };
  16046. /**
  16047. * Will return all nodes that have this node as ascendant
  16048. * @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
  16049. * @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
  16050. * @return all children nodes of all types
  16051. */
  16052. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16053. var results = new Array();
  16054. this._getDescendants(results, directDescendantsOnly, predicate);
  16055. return results;
  16056. };
  16057. /**
  16058. * Get all child-meshes of this node
  16059. * @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
  16060. * @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
  16061. * @returns an array of {BABYLON.AbstractMesh}
  16062. */
  16063. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16064. var results = [];
  16065. this._getDescendants(results, directDescendantsOnly, function (node) {
  16066. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16067. });
  16068. return results;
  16069. };
  16070. /**
  16071. * Get all child-transformNodes of this node
  16072. * @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
  16073. * @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
  16074. * @returns an array of {BABYLON.TransformNode}
  16075. */
  16076. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16077. var results = [];
  16078. this._getDescendants(results, directDescendantsOnly, function (node) {
  16079. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16080. });
  16081. return results;
  16082. };
  16083. /**
  16084. * Get all direct children of this node
  16085. * @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
  16086. * @returns an array of {BABYLON.Node}
  16087. */
  16088. Node.prototype.getChildren = function (predicate) {
  16089. return this.getDescendants(true, predicate);
  16090. };
  16091. /** @ignore */
  16092. Node.prototype._setReady = function (state) {
  16093. if (state === this._isReady) {
  16094. return;
  16095. }
  16096. if (!state) {
  16097. this._isReady = false;
  16098. return;
  16099. }
  16100. if (this.onReady) {
  16101. this.onReady(this);
  16102. }
  16103. this._isReady = true;
  16104. };
  16105. /**
  16106. * Get an animation by name
  16107. * @param name defines the name of the animation to look for
  16108. * @returns null if not found else the requested animation
  16109. */
  16110. Node.prototype.getAnimationByName = function (name) {
  16111. for (var i = 0; i < this.animations.length; i++) {
  16112. var animation = this.animations[i];
  16113. if (animation.name === name) {
  16114. return animation;
  16115. }
  16116. }
  16117. return null;
  16118. };
  16119. /**
  16120. * Creates an animation range for this node
  16121. * @param name defines the name of the range
  16122. * @param from defines the starting key
  16123. * @param to defines the end key
  16124. */
  16125. Node.prototype.createAnimationRange = function (name, from, to) {
  16126. // check name not already in use
  16127. if (!this._ranges[name]) {
  16128. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16129. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16130. if (this.animations[i]) {
  16131. this.animations[i].createRange(name, from, to);
  16132. }
  16133. }
  16134. }
  16135. };
  16136. /**
  16137. * Delete a specific animation range
  16138. * @param name defines the name of the range to delete
  16139. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16140. */
  16141. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16142. if (deleteFrames === void 0) { deleteFrames = true; }
  16143. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16144. if (this.animations[i]) {
  16145. this.animations[i].deleteRange(name, deleteFrames);
  16146. }
  16147. }
  16148. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16149. };
  16150. /**
  16151. * Get an animation range by name
  16152. * @param name defines the name of the animation range to look for
  16153. * @returns null if not found else the requested animation range
  16154. */
  16155. Node.prototype.getAnimationRange = function (name) {
  16156. return this._ranges[name];
  16157. };
  16158. /**
  16159. * Will start the animation sequence
  16160. * @param name defines the range frames for animation sequence
  16161. * @param loop defines if the animation should loop (false by default)
  16162. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16163. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16164. * @returns the object created for this animation. If range does not exist, it will return null
  16165. */
  16166. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16167. var range = this.getAnimationRange(name);
  16168. if (!range) {
  16169. return null;
  16170. }
  16171. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16172. };
  16173. /**
  16174. * Serialize animation ranges into a JSON compatible object
  16175. * @returns serialization object
  16176. */
  16177. Node.prototype.serializeAnimationRanges = function () {
  16178. var serializationRanges = [];
  16179. for (var name in this._ranges) {
  16180. var localRange = this._ranges[name];
  16181. if (!localRange) {
  16182. continue;
  16183. }
  16184. var range = {};
  16185. range.name = name;
  16186. range.from = localRange.from;
  16187. range.to = localRange.to;
  16188. serializationRanges.push(range);
  16189. }
  16190. return serializationRanges;
  16191. };
  16192. /**
  16193. * Computes the world matrix of the node
  16194. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16195. * @returns the world matrix
  16196. */
  16197. Node.prototype.computeWorldMatrix = function (force) {
  16198. return BABYLON.Matrix.Identity();
  16199. };
  16200. /**
  16201. * Releases resources associated with this node.
  16202. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16203. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16204. */
  16205. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16206. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16207. if (!doNotRecurse) {
  16208. var nodes = this.getDescendants(true);
  16209. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16210. var node = nodes_1[_i];
  16211. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16212. }
  16213. }
  16214. else {
  16215. var transformNodes = this.getChildTransformNodes(true);
  16216. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16217. var transformNode = transformNodes_1[_a];
  16218. transformNode.parent = null;
  16219. transformNode.computeWorldMatrix(true);
  16220. }
  16221. }
  16222. this.parent = null;
  16223. // Callback
  16224. this.onDisposeObservable.notifyObservers(this);
  16225. this.onDisposeObservable.clear();
  16226. // Behaviors
  16227. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16228. var behavior = _c[_b];
  16229. behavior.detach();
  16230. }
  16231. this._behaviors = [];
  16232. this._isDisposed = true;
  16233. };
  16234. /**
  16235. * Parse animation range data from a serialization object and store them into a given node
  16236. * @param node defines where to store the animation ranges
  16237. * @param parsedNode defines the serialization object to read data from
  16238. * @param scene defines the hosting scene
  16239. */
  16240. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16241. if (parsedNode.ranges) {
  16242. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16243. var data = parsedNode.ranges[index];
  16244. node.createAnimationRange(data.name, data.from, data.to);
  16245. }
  16246. }
  16247. };
  16248. __decorate([
  16249. BABYLON.serialize()
  16250. ], Node.prototype, "name", void 0);
  16251. __decorate([
  16252. BABYLON.serialize()
  16253. ], Node.prototype, "id", void 0);
  16254. __decorate([
  16255. BABYLON.serialize()
  16256. ], Node.prototype, "uniqueId", void 0);
  16257. __decorate([
  16258. BABYLON.serialize()
  16259. ], Node.prototype, "state", void 0);
  16260. __decorate([
  16261. BABYLON.serialize()
  16262. ], Node.prototype, "metadata", void 0);
  16263. return Node;
  16264. }());
  16265. BABYLON.Node = Node;
  16266. })(BABYLON || (BABYLON = {}));
  16267. //# sourceMappingURL=babylon.node.js.map
  16268. "use strict";
  16269. var BABYLON;
  16270. (function (BABYLON) {
  16271. var BoundingSphere = /** @class */ (function () {
  16272. function BoundingSphere(minimum, maximum) {
  16273. this.minimum = minimum;
  16274. this.maximum = maximum;
  16275. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16276. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16277. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16278. this.radius = distance * 0.5;
  16279. this.centerWorld = BABYLON.Vector3.Zero();
  16280. this._update(BABYLON.Matrix.Identity());
  16281. }
  16282. // Methods
  16283. BoundingSphere.prototype._update = function (world) {
  16284. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16285. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16286. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16287. };
  16288. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16289. for (var i = 0; i < 6; i++) {
  16290. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16291. return false;
  16292. }
  16293. return true;
  16294. };
  16295. BoundingSphere.prototype.intersectsPoint = function (point) {
  16296. var x = this.centerWorld.x - point.x;
  16297. var y = this.centerWorld.y - point.y;
  16298. var z = this.centerWorld.z - point.z;
  16299. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16300. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16301. return false;
  16302. return true;
  16303. };
  16304. // Statics
  16305. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16306. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16307. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16308. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16309. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16310. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16311. return false;
  16312. return true;
  16313. };
  16314. return BoundingSphere;
  16315. }());
  16316. BABYLON.BoundingSphere = BoundingSphere;
  16317. })(BABYLON || (BABYLON = {}));
  16318. //# sourceMappingURL=babylon.boundingSphere.js.map
  16319. "use strict";
  16320. var BABYLON;
  16321. (function (BABYLON) {
  16322. var BoundingBox = /** @class */ (function () {
  16323. function BoundingBox(minimum, maximum) {
  16324. this.minimum = minimum;
  16325. this.maximum = maximum;
  16326. this.vectors = new Array();
  16327. this.vectorsWorld = new Array();
  16328. // Bounding vectors
  16329. this.vectors.push(this.minimum.clone());
  16330. this.vectors.push(this.maximum.clone());
  16331. this.vectors.push(this.minimum.clone());
  16332. this.vectors[2].x = this.maximum.x;
  16333. this.vectors.push(this.minimum.clone());
  16334. this.vectors[3].y = this.maximum.y;
  16335. this.vectors.push(this.minimum.clone());
  16336. this.vectors[4].z = this.maximum.z;
  16337. this.vectors.push(this.maximum.clone());
  16338. this.vectors[5].z = this.minimum.z;
  16339. this.vectors.push(this.maximum.clone());
  16340. this.vectors[6].x = this.minimum.x;
  16341. this.vectors.push(this.maximum.clone());
  16342. this.vectors[7].y = this.minimum.y;
  16343. // OBB
  16344. this.center = this.maximum.add(this.minimum).scale(0.5);
  16345. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16346. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16347. // World
  16348. for (var index = 0; index < this.vectors.length; index++) {
  16349. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16350. }
  16351. this.minimumWorld = BABYLON.Vector3.Zero();
  16352. this.maximumWorld = BABYLON.Vector3.Zero();
  16353. this.centerWorld = BABYLON.Vector3.Zero();
  16354. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16355. this._update(BABYLON.Matrix.Identity());
  16356. }
  16357. // Methods
  16358. BoundingBox.prototype.getWorldMatrix = function () {
  16359. return this._worldMatrix;
  16360. };
  16361. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16362. this._worldMatrix.copyFrom(matrix);
  16363. return this;
  16364. };
  16365. BoundingBox.prototype._update = function (world) {
  16366. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16367. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16368. for (var index = 0; index < this.vectors.length; index++) {
  16369. var v = this.vectorsWorld[index];
  16370. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16371. if (v.x < this.minimumWorld.x)
  16372. this.minimumWorld.x = v.x;
  16373. if (v.y < this.minimumWorld.y)
  16374. this.minimumWorld.y = v.y;
  16375. if (v.z < this.minimumWorld.z)
  16376. this.minimumWorld.z = v.z;
  16377. if (v.x > this.maximumWorld.x)
  16378. this.maximumWorld.x = v.x;
  16379. if (v.y > this.maximumWorld.y)
  16380. this.maximumWorld.y = v.y;
  16381. if (v.z > this.maximumWorld.z)
  16382. this.maximumWorld.z = v.z;
  16383. }
  16384. // Extend
  16385. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16386. this.extendSizeWorld.scaleInPlace(0.5);
  16387. // OBB
  16388. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16389. this.centerWorld.scaleInPlace(0.5);
  16390. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16391. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16392. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16393. this._worldMatrix = world;
  16394. };
  16395. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16396. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16397. };
  16398. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16399. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16400. };
  16401. BoundingBox.prototype.intersectsPoint = function (point) {
  16402. var delta = -BABYLON.Epsilon;
  16403. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16404. return false;
  16405. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16406. return false;
  16407. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16408. return false;
  16409. return true;
  16410. };
  16411. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16412. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16413. };
  16414. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16415. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16416. return false;
  16417. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16418. return false;
  16419. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16420. return false;
  16421. return true;
  16422. };
  16423. // Statics
  16424. BoundingBox.Intersects = function (box0, box1) {
  16425. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16426. return false;
  16427. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16428. return false;
  16429. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16430. return false;
  16431. return true;
  16432. };
  16433. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16434. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16435. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16436. return (num <= (sphereRadius * sphereRadius));
  16437. };
  16438. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16439. for (var p = 0; p < 6; p++) {
  16440. for (var i = 0; i < 8; i++) {
  16441. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16442. return false;
  16443. }
  16444. }
  16445. }
  16446. return true;
  16447. };
  16448. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16449. for (var p = 0; p < 6; p++) {
  16450. var inCount = 8;
  16451. for (var i = 0; i < 8; i++) {
  16452. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16453. --inCount;
  16454. }
  16455. else {
  16456. break;
  16457. }
  16458. }
  16459. if (inCount === 0)
  16460. return false;
  16461. }
  16462. return true;
  16463. };
  16464. return BoundingBox;
  16465. }());
  16466. BABYLON.BoundingBox = BoundingBox;
  16467. })(BABYLON || (BABYLON = {}));
  16468. //# sourceMappingURL=babylon.boundingBox.js.map
  16469. "use strict";
  16470. var BABYLON;
  16471. (function (BABYLON) {
  16472. var computeBoxExtents = function (axis, box) {
  16473. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16474. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16475. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16476. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16477. var r = r0 + r1 + r2;
  16478. return {
  16479. min: p - r,
  16480. max: p + r
  16481. };
  16482. };
  16483. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16484. var axisOverlap = function (axis, box0, box1) {
  16485. var result0 = computeBoxExtents(axis, box0);
  16486. var result1 = computeBoxExtents(axis, box1);
  16487. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16488. };
  16489. var BoundingInfo = /** @class */ (function () {
  16490. function BoundingInfo(minimum, maximum) {
  16491. this.minimum = minimum;
  16492. this.maximum = maximum;
  16493. this._isLocked = false;
  16494. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16495. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16496. }
  16497. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16498. get: function () {
  16499. return this._isLocked;
  16500. },
  16501. set: function (value) {
  16502. this._isLocked = value;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. // Methods
  16508. BoundingInfo.prototype.update = function (world) {
  16509. if (this._isLocked) {
  16510. return;
  16511. }
  16512. this.boundingBox._update(world);
  16513. this.boundingSphere._update(world);
  16514. };
  16515. /**
  16516. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16517. * @param center New center of the bounding info
  16518. * @param extend New extend of the bounding info
  16519. */
  16520. BoundingInfo.prototype.centerOn = function (center, extend) {
  16521. this.minimum = center.subtract(extend);
  16522. this.maximum = center.add(extend);
  16523. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16524. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16525. return this;
  16526. };
  16527. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16528. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16529. return false;
  16530. return this.boundingBox.isInFrustum(frustumPlanes);
  16531. };
  16532. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16533. /**
  16534. * Gets the world distance between the min and max points of the bounding box
  16535. */
  16536. get: function () {
  16537. var boundingBox = this.boundingBox;
  16538. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16539. return size.length();
  16540. },
  16541. enumerable: true,
  16542. configurable: true
  16543. });
  16544. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16545. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16546. };
  16547. BoundingInfo.prototype._checkCollision = function (collider) {
  16548. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16549. };
  16550. BoundingInfo.prototype.intersectsPoint = function (point) {
  16551. if (!this.boundingSphere.centerWorld) {
  16552. return false;
  16553. }
  16554. if (!this.boundingSphere.intersectsPoint(point)) {
  16555. return false;
  16556. }
  16557. if (!this.boundingBox.intersectsPoint(point)) {
  16558. return false;
  16559. }
  16560. return true;
  16561. };
  16562. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16563. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16564. return false;
  16565. }
  16566. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16567. return false;
  16568. }
  16569. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16570. return false;
  16571. }
  16572. if (!precise) {
  16573. return true;
  16574. }
  16575. var box0 = this.boundingBox;
  16576. var box1 = boundingInfo.boundingBox;
  16577. if (!axisOverlap(box0.directions[0], box0, box1))
  16578. return false;
  16579. if (!axisOverlap(box0.directions[1], box0, box1))
  16580. return false;
  16581. if (!axisOverlap(box0.directions[2], box0, box1))
  16582. return false;
  16583. if (!axisOverlap(box1.directions[0], box0, box1))
  16584. return false;
  16585. if (!axisOverlap(box1.directions[1], box0, box1))
  16586. return false;
  16587. if (!axisOverlap(box1.directions[2], box0, box1))
  16588. return false;
  16589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16590. return false;
  16591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16592. return false;
  16593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16594. return false;
  16595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16596. return false;
  16597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16598. return false;
  16599. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16600. return false;
  16601. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16602. return false;
  16603. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16604. return false;
  16605. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16606. return false;
  16607. return true;
  16608. };
  16609. return BoundingInfo;
  16610. }());
  16611. BABYLON.BoundingInfo = BoundingInfo;
  16612. })(BABYLON || (BABYLON = {}));
  16613. //# sourceMappingURL=babylon.boundingInfo.js.map
  16614. "use strict";
  16615. var BABYLON;
  16616. (function (BABYLON) {
  16617. var TransformNode = /** @class */ (function (_super) {
  16618. __extends(TransformNode, _super);
  16619. function TransformNode(name, scene, isPure) {
  16620. if (scene === void 0) { scene = null; }
  16621. if (isPure === void 0) { isPure = true; }
  16622. var _this = _super.call(this, name, scene) || this;
  16623. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16624. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16625. _this._up = new BABYLON.Vector3(0, 1, 0);
  16626. _this._right = new BABYLON.Vector3(1, 0, 0);
  16627. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16628. // Properties
  16629. _this._rotation = BABYLON.Vector3.Zero();
  16630. _this._scaling = BABYLON.Vector3.One();
  16631. _this._isDirty = false;
  16632. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16633. _this.scalingDeterminant = 1;
  16634. _this.infiniteDistance = false;
  16635. _this.position = BABYLON.Vector3.Zero();
  16636. _this._localWorld = BABYLON.Matrix.Zero();
  16637. _this._worldMatrix = BABYLON.Matrix.Zero();
  16638. _this._worldMatrixDeterminant = 0;
  16639. _this._absolutePosition = BABYLON.Vector3.Zero();
  16640. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16641. _this._postMultiplyPivotMatrix = false;
  16642. _this._isWorldMatrixFrozen = false;
  16643. /**
  16644. * An event triggered after the world matrix is updated
  16645. * @type {BABYLON.Observable}
  16646. */
  16647. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16648. _this._nonUniformScaling = false;
  16649. if (isPure) {
  16650. _this.getScene().addTransformNode(_this);
  16651. }
  16652. return _this;
  16653. }
  16654. /**
  16655. * Gets a string idenfifying the name of the class
  16656. * @returns "TransformNode" string
  16657. */
  16658. TransformNode.prototype.getClassName = function () {
  16659. return "TransformNode";
  16660. };
  16661. Object.defineProperty(TransformNode.prototype, "rotation", {
  16662. /**
  16663. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16664. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16665. * Default : (0.0, 0.0, 0.0)
  16666. */
  16667. get: function () {
  16668. return this._rotation;
  16669. },
  16670. set: function (newRotation) {
  16671. this._rotation = newRotation;
  16672. },
  16673. enumerable: true,
  16674. configurable: true
  16675. });
  16676. Object.defineProperty(TransformNode.prototype, "scaling", {
  16677. /**
  16678. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16679. * Default : (1.0, 1.0, 1.0)
  16680. */
  16681. get: function () {
  16682. return this._scaling;
  16683. },
  16684. /**
  16685. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16686. * Default : (1.0, 1.0, 1.0)
  16687. */
  16688. set: function (newScaling) {
  16689. this._scaling = newScaling;
  16690. },
  16691. enumerable: true,
  16692. configurable: true
  16693. });
  16694. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16695. /**
  16696. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16697. * It's null by default.
  16698. * 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)
  16699. */
  16700. get: function () {
  16701. return this._rotationQuaternion;
  16702. },
  16703. set: function (quaternion) {
  16704. this._rotationQuaternion = quaternion;
  16705. //reset the rotation vector.
  16706. if (quaternion && this.rotation.length()) {
  16707. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16708. }
  16709. },
  16710. enumerable: true,
  16711. configurable: true
  16712. });
  16713. Object.defineProperty(TransformNode.prototype, "forward", {
  16714. /**
  16715. * The forward direction of that transform in world space.
  16716. */
  16717. get: function () {
  16718. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Object.defineProperty(TransformNode.prototype, "up", {
  16724. /**
  16725. * The up direction of that transform in world space.
  16726. */
  16727. get: function () {
  16728. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. Object.defineProperty(TransformNode.prototype, "right", {
  16734. /**
  16735. * The right direction of that transform in world space.
  16736. */
  16737. get: function () {
  16738. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16739. },
  16740. enumerable: true,
  16741. configurable: true
  16742. });
  16743. /**
  16744. * Returns the latest update of the World matrix
  16745. * Returns a Matrix.
  16746. */
  16747. TransformNode.prototype.getWorldMatrix = function () {
  16748. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16749. this.computeWorldMatrix();
  16750. }
  16751. return this._worldMatrix;
  16752. };
  16753. /**
  16754. * Returns the latest update of the World matrix determinant.
  16755. */
  16756. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16757. return this._worldMatrixDeterminant;
  16758. };
  16759. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16760. /**
  16761. * Returns directly the latest state of the mesh World matrix.
  16762. * A Matrix is returned.
  16763. */
  16764. get: function () {
  16765. return this._worldMatrix;
  16766. },
  16767. enumerable: true,
  16768. configurable: true
  16769. });
  16770. /**
  16771. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16772. * Returns the TransformNode.
  16773. */
  16774. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16775. this._poseMatrix.copyFrom(matrix);
  16776. return this;
  16777. };
  16778. /**
  16779. * Returns the mesh Pose matrix.
  16780. * Returned object : Matrix
  16781. */
  16782. TransformNode.prototype.getPoseMatrix = function () {
  16783. return this._poseMatrix;
  16784. };
  16785. TransformNode.prototype._isSynchronized = function () {
  16786. if (this._isDirty) {
  16787. return false;
  16788. }
  16789. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16790. return false;
  16791. if (this._cache.pivotMatrixUpdated) {
  16792. return false;
  16793. }
  16794. if (this.infiniteDistance) {
  16795. return false;
  16796. }
  16797. if (!this._cache.position.equals(this.position))
  16798. return false;
  16799. if (this.rotationQuaternion) {
  16800. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16801. return false;
  16802. }
  16803. if (!this._cache.rotation.equals(this.rotation))
  16804. return false;
  16805. if (!this._cache.scaling.equals(this.scaling))
  16806. return false;
  16807. return true;
  16808. };
  16809. TransformNode.prototype._initCache = function () {
  16810. _super.prototype._initCache.call(this);
  16811. this._cache.localMatrixUpdated = false;
  16812. this._cache.position = BABYLON.Vector3.Zero();
  16813. this._cache.scaling = BABYLON.Vector3.Zero();
  16814. this._cache.rotation = BABYLON.Vector3.Zero();
  16815. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16816. this._cache.billboardMode = -1;
  16817. };
  16818. TransformNode.prototype.markAsDirty = function (property) {
  16819. if (property === "rotation") {
  16820. this.rotationQuaternion = null;
  16821. }
  16822. this._currentRenderId = Number.MAX_VALUE;
  16823. this._isDirty = true;
  16824. return this;
  16825. };
  16826. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16827. /**
  16828. * Returns the current mesh absolute position.
  16829. * Retuns a Vector3.
  16830. */
  16831. get: function () {
  16832. return this._absolutePosition;
  16833. },
  16834. enumerable: true,
  16835. configurable: true
  16836. });
  16837. /**
  16838. * Sets a new matrix to apply before all other transformation
  16839. * @param matrix defines the transform matrix
  16840. * @returns the current TransformNode
  16841. */
  16842. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16843. return this.setPivotMatrix(matrix, false);
  16844. };
  16845. /**
  16846. * Sets a new pivot matrix to the current node
  16847. * @param matrix defines the new pivot matrix to use
  16848. * @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
  16849. * @returns the current TransformNode
  16850. */
  16851. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16852. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16853. this._pivotMatrix = matrix.clone();
  16854. this._cache.pivotMatrixUpdated = true;
  16855. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16856. if (this._postMultiplyPivotMatrix) {
  16857. if (!this._pivotMatrixInverse) {
  16858. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16859. }
  16860. else {
  16861. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16862. }
  16863. }
  16864. return this;
  16865. };
  16866. /**
  16867. * Returns the mesh pivot matrix.
  16868. * Default : Identity.
  16869. * A Matrix is returned.
  16870. */
  16871. TransformNode.prototype.getPivotMatrix = function () {
  16872. return this._pivotMatrix;
  16873. };
  16874. /**
  16875. * Prevents the World matrix to be computed any longer.
  16876. * Returns the TransformNode.
  16877. */
  16878. TransformNode.prototype.freezeWorldMatrix = function () {
  16879. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16880. this.computeWorldMatrix(true);
  16881. this._isWorldMatrixFrozen = true;
  16882. return this;
  16883. };
  16884. /**
  16885. * Allows back the World matrix computation.
  16886. * Returns the TransformNode.
  16887. */
  16888. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16889. this._isWorldMatrixFrozen = false;
  16890. this.computeWorldMatrix(true);
  16891. return this;
  16892. };
  16893. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16894. /**
  16895. * True if the World matrix has been frozen.
  16896. * Returns a boolean.
  16897. */
  16898. get: function () {
  16899. return this._isWorldMatrixFrozen;
  16900. },
  16901. enumerable: true,
  16902. configurable: true
  16903. });
  16904. /**
  16905. * Retuns the mesh absolute position in the World.
  16906. * Returns a Vector3.
  16907. */
  16908. TransformNode.prototype.getAbsolutePosition = function () {
  16909. this.computeWorldMatrix();
  16910. return this._absolutePosition;
  16911. };
  16912. /**
  16913. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16914. * Returns the TransformNode.
  16915. */
  16916. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16917. if (!absolutePosition) {
  16918. return this;
  16919. }
  16920. var absolutePositionX;
  16921. var absolutePositionY;
  16922. var absolutePositionZ;
  16923. if (absolutePosition.x === undefined) {
  16924. if (arguments.length < 3) {
  16925. return this;
  16926. }
  16927. absolutePositionX = arguments[0];
  16928. absolutePositionY = arguments[1];
  16929. absolutePositionZ = arguments[2];
  16930. }
  16931. else {
  16932. absolutePositionX = absolutePosition.x;
  16933. absolutePositionY = absolutePosition.y;
  16934. absolutePositionZ = absolutePosition.z;
  16935. }
  16936. if (this.parent) {
  16937. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16938. invertParentWorldMatrix.invert();
  16939. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16940. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16941. }
  16942. else {
  16943. this.position.x = absolutePositionX;
  16944. this.position.y = absolutePositionY;
  16945. this.position.z = absolutePositionZ;
  16946. }
  16947. return this;
  16948. };
  16949. /**
  16950. * Sets the mesh position in its local space.
  16951. * Returns the TransformNode.
  16952. */
  16953. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16954. this.computeWorldMatrix();
  16955. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16956. return this;
  16957. };
  16958. /**
  16959. * Returns the mesh position in the local space from the current World matrix values.
  16960. * Returns a new Vector3.
  16961. */
  16962. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16963. this.computeWorldMatrix();
  16964. var invLocalWorldMatrix = this._localWorld.clone();
  16965. invLocalWorldMatrix.invert();
  16966. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16967. };
  16968. /**
  16969. * Translates the mesh along the passed Vector3 in its local space.
  16970. * Returns the TransformNode.
  16971. */
  16972. TransformNode.prototype.locallyTranslate = function (vector3) {
  16973. this.computeWorldMatrix(true);
  16974. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16975. return this;
  16976. };
  16977. /**
  16978. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16979. * @param targetPoint the position (must be in same space as current mesh) to look at
  16980. * @param yawCor optional yaw (y-axis) correction in radians
  16981. * @param pitchCor optional pitch (x-axis) correction in radians
  16982. * @param rollCor optional roll (z-axis) correction in radians
  16983. * @param space the choosen space of the target
  16984. * @returns the TransformNode.
  16985. */
  16986. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16987. if (yawCor === void 0) { yawCor = 0; }
  16988. if (pitchCor === void 0) { pitchCor = 0; }
  16989. if (rollCor === void 0) { rollCor = 0; }
  16990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16991. var dv = TransformNode._lookAtVectorCache;
  16992. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16993. targetPoint.subtractToRef(pos, dv);
  16994. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16995. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16996. var pitch = Math.atan2(dv.y, len);
  16997. if (this.rotationQuaternion) {
  16998. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16999. }
  17000. else {
  17001. this.rotation.x = pitch + pitchCor;
  17002. this.rotation.y = yaw + yawCor;
  17003. this.rotation.z = rollCor;
  17004. }
  17005. return this;
  17006. };
  17007. /**
  17008. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  17009. * This Vector3 is expressed in the World space.
  17010. */
  17011. TransformNode.prototype.getDirection = function (localAxis) {
  17012. var result = BABYLON.Vector3.Zero();
  17013. this.getDirectionToRef(localAxis, result);
  17014. return result;
  17015. };
  17016. /**
  17017. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  17018. * localAxis is expressed in the mesh local space.
  17019. * result is computed in the Wordl space from the mesh World matrix.
  17020. * Returns the TransformNode.
  17021. */
  17022. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  17023. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17024. return this;
  17025. };
  17026. /**
  17027. * Sets a new pivot point to the current node
  17028. * @param point defines the new pivot point to use
  17029. * @param space defines if the point is in world or local space (local by default)
  17030. * @returns the current TransformNode
  17031. */
  17032. TransformNode.prototype.setPivotPoint = function (point, space) {
  17033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17034. if (this.getScene().getRenderId() == 0) {
  17035. this.computeWorldMatrix(true);
  17036. }
  17037. var wm = this.getWorldMatrix();
  17038. if (space == BABYLON.Space.WORLD) {
  17039. var tmat = BABYLON.Tmp.Matrix[0];
  17040. wm.invertToRef(tmat);
  17041. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  17042. }
  17043. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  17044. };
  17045. /**
  17046. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  17047. */
  17048. TransformNode.prototype.getPivotPoint = function () {
  17049. var point = BABYLON.Vector3.Zero();
  17050. this.getPivotPointToRef(point);
  17051. return point;
  17052. };
  17053. /**
  17054. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17055. * Returns the TransformNode.
  17056. */
  17057. TransformNode.prototype.getPivotPointToRef = function (result) {
  17058. result.x = -this._pivotMatrix.m[12];
  17059. result.y = -this._pivotMatrix.m[13];
  17060. result.z = -this._pivotMatrix.m[14];
  17061. return this;
  17062. };
  17063. /**
  17064. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17065. */
  17066. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17067. var point = BABYLON.Vector3.Zero();
  17068. this.getAbsolutePivotPointToRef(point);
  17069. return point;
  17070. };
  17071. /**
  17072. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17073. * Returns the TransformNode.
  17074. */
  17075. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17076. result.x = this._pivotMatrix.m[12];
  17077. result.y = this._pivotMatrix.m[13];
  17078. result.z = this._pivotMatrix.m[14];
  17079. this.getPivotPointToRef(result);
  17080. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17081. return this;
  17082. };
  17083. /**
  17084. * Defines the passed node as the parent of the current node.
  17085. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17086. * Returns the TransformNode.
  17087. */
  17088. TransformNode.prototype.setParent = function (node) {
  17089. if (node === null) {
  17090. var rotation = BABYLON.Tmp.Quaternion[0];
  17091. var position = BABYLON.Tmp.Vector3[0];
  17092. var scale = BABYLON.Tmp.Vector3[1];
  17093. if (this.parent && this.parent.computeWorldMatrix) {
  17094. this.parent.computeWorldMatrix(true);
  17095. }
  17096. this.computeWorldMatrix(true);
  17097. this.getWorldMatrix().decompose(scale, rotation, position);
  17098. if (this.rotationQuaternion) {
  17099. this.rotationQuaternion.copyFrom(rotation);
  17100. }
  17101. else {
  17102. rotation.toEulerAnglesToRef(this.rotation);
  17103. }
  17104. this.scaling.x = scale.x;
  17105. this.scaling.y = scale.y;
  17106. this.scaling.z = scale.z;
  17107. this.position.x = position.x;
  17108. this.position.y = position.y;
  17109. this.position.z = position.z;
  17110. }
  17111. else {
  17112. var rotation = BABYLON.Tmp.Quaternion[0];
  17113. var position = BABYLON.Tmp.Vector3[0];
  17114. var scale = BABYLON.Tmp.Vector3[1];
  17115. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17116. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17117. this.computeWorldMatrix(true);
  17118. node.computeWorldMatrix(true);
  17119. node.getWorldMatrix().invertToRef(invParentMatrix);
  17120. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17121. diffMatrix.decompose(scale, rotation, position);
  17122. if (this.rotationQuaternion) {
  17123. this.rotationQuaternion.copyFrom(rotation);
  17124. }
  17125. else {
  17126. rotation.toEulerAnglesToRef(this.rotation);
  17127. }
  17128. this.position.x = position.x;
  17129. this.position.y = position.y;
  17130. this.position.z = position.z;
  17131. this.scaling.x = scale.x;
  17132. this.scaling.y = scale.y;
  17133. this.scaling.z = scale.z;
  17134. }
  17135. this.parent = node;
  17136. return this;
  17137. };
  17138. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17139. get: function () {
  17140. return this._nonUniformScaling;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17146. if (this._nonUniformScaling === value) {
  17147. return false;
  17148. }
  17149. this._nonUniformScaling = true;
  17150. return true;
  17151. };
  17152. /**
  17153. * Attach the current TransformNode to another TransformNode associated with a bone
  17154. * @param bone Bone affecting the TransformNode
  17155. * @param affectedTransformNode TransformNode associated with the bone
  17156. */
  17157. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17158. this._transformToBoneReferal = affectedTransformNode;
  17159. this.parent = bone;
  17160. if (bone.getWorldMatrix().determinant() < 0) {
  17161. this.scalingDeterminant *= -1;
  17162. }
  17163. return this;
  17164. };
  17165. TransformNode.prototype.detachFromBone = function () {
  17166. if (!this.parent) {
  17167. return this;
  17168. }
  17169. if (this.parent.getWorldMatrix().determinant() < 0) {
  17170. this.scalingDeterminant *= -1;
  17171. }
  17172. this._transformToBoneReferal = null;
  17173. this.parent = null;
  17174. return this;
  17175. };
  17176. /**
  17177. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17178. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17179. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17180. * The passed axis is also normalized.
  17181. * Returns the TransformNode.
  17182. */
  17183. TransformNode.prototype.rotate = function (axis, amount, space) {
  17184. axis.normalize();
  17185. if (!this.rotationQuaternion) {
  17186. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17187. this.rotation = BABYLON.Vector3.Zero();
  17188. }
  17189. var rotationQuaternion;
  17190. if (!space || space === BABYLON.Space.LOCAL) {
  17191. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17192. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17193. }
  17194. else {
  17195. if (this.parent) {
  17196. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17197. invertParentWorldMatrix.invert();
  17198. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17199. }
  17200. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17201. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17202. }
  17203. return this;
  17204. };
  17205. /**
  17206. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17207. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17208. * The passed axis is also normalized.
  17209. * Returns the TransformNode.
  17210. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17211. */
  17212. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17213. axis.normalize();
  17214. if (!this.rotationQuaternion) {
  17215. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17216. this.rotation.copyFromFloats(0, 0, 0);
  17217. }
  17218. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17219. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17220. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17221. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17222. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17223. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17224. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17225. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17226. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17227. return this;
  17228. };
  17229. /**
  17230. * Translates the mesh along the axis vector for the passed distance in the given space.
  17231. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17232. * Returns the TransformNode.
  17233. */
  17234. TransformNode.prototype.translate = function (axis, distance, space) {
  17235. var displacementVector = axis.scale(distance);
  17236. if (!space || space === BABYLON.Space.LOCAL) {
  17237. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17238. this.setPositionWithLocalVector(tempV3);
  17239. }
  17240. else {
  17241. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17242. }
  17243. return this;
  17244. };
  17245. /**
  17246. * Adds a rotation step to the mesh current rotation.
  17247. * x, y, z are Euler angles expressed in radians.
  17248. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17249. * This means this rotation is made in the mesh local space only.
  17250. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17251. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17252. * ```javascript
  17253. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17254. * ```
  17255. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17256. * 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.
  17257. * Returns the TransformNode.
  17258. */
  17259. TransformNode.prototype.addRotation = function (x, y, z) {
  17260. var rotationQuaternion;
  17261. if (this.rotationQuaternion) {
  17262. rotationQuaternion = this.rotationQuaternion;
  17263. }
  17264. else {
  17265. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17266. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17267. }
  17268. var accumulation = BABYLON.Tmp.Quaternion[0];
  17269. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17270. rotationQuaternion.multiplyInPlace(accumulation);
  17271. if (!this.rotationQuaternion) {
  17272. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17273. }
  17274. return this;
  17275. };
  17276. /**
  17277. * Computes the mesh World matrix and returns it.
  17278. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17279. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17280. * If the parameter `force`is set to `true`, the actual computation is done.
  17281. * Returns the mesh World Matrix.
  17282. */
  17283. TransformNode.prototype.computeWorldMatrix = function (force) {
  17284. if (this._isWorldMatrixFrozen) {
  17285. return this._worldMatrix;
  17286. }
  17287. if (!force && this.isSynchronized(true)) {
  17288. this._currentRenderId = this.getScene().getRenderId();
  17289. return this._worldMatrix;
  17290. }
  17291. this._cache.position.copyFrom(this.position);
  17292. this._cache.scaling.copyFrom(this.scaling);
  17293. this._cache.pivotMatrixUpdated = false;
  17294. this._cache.billboardMode = this.billboardMode;
  17295. this._currentRenderId = this.getScene().getRenderId();
  17296. this._childRenderId = this.getScene().getRenderId();
  17297. this._isDirty = false;
  17298. // Scaling
  17299. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17300. // Rotation
  17301. //rotate, if quaternion is set and rotation was used
  17302. if (this.rotationQuaternion) {
  17303. var len = this.rotation.length();
  17304. if (len) {
  17305. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17306. this.rotation.copyFromFloats(0, 0, 0);
  17307. }
  17308. }
  17309. if (this.rotationQuaternion) {
  17310. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17311. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17312. }
  17313. else {
  17314. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17315. this._cache.rotation.copyFrom(this.rotation);
  17316. }
  17317. // Translation
  17318. var camera = this.getScene().activeCamera;
  17319. if (this.infiniteDistance && !this.parent && camera) {
  17320. var cameraWorldMatrix = camera.getWorldMatrix();
  17321. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17322. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17323. }
  17324. else {
  17325. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17326. }
  17327. // Composing transformations
  17328. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17329. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17330. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17331. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17332. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17333. // Need to decompose each rotation here
  17334. var currentPosition = BABYLON.Tmp.Vector3[3];
  17335. if (this.parent && this.parent.getWorldMatrix) {
  17336. if (this._transformToBoneReferal) {
  17337. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17338. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17339. }
  17340. else {
  17341. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17342. }
  17343. }
  17344. else {
  17345. currentPosition.copyFrom(this.position);
  17346. }
  17347. currentPosition.subtractInPlace(camera.globalPosition);
  17348. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17349. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17350. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17351. }
  17352. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17353. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17354. }
  17355. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17356. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17357. }
  17358. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17359. }
  17360. else {
  17361. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17362. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17363. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17364. }
  17365. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17366. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17367. }
  17368. // Local world
  17369. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17370. // Parent
  17371. if (this.parent && this.parent.getWorldMatrix) {
  17372. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17373. if (this._transformToBoneReferal) {
  17374. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17375. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17376. }
  17377. else {
  17378. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17379. }
  17380. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17381. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17382. this._worldMatrix.copyFrom(this._localWorld);
  17383. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17384. }
  17385. else {
  17386. if (this._transformToBoneReferal) {
  17387. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17388. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17389. }
  17390. else {
  17391. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17392. }
  17393. }
  17394. this._markSyncedWithParent();
  17395. }
  17396. else {
  17397. this._worldMatrix.copyFrom(this._localWorld);
  17398. }
  17399. // Post multiply inverse of pivotMatrix
  17400. if (this._postMultiplyPivotMatrix) {
  17401. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17402. }
  17403. // Normal matrix
  17404. if (this.scaling.isNonUniform) {
  17405. this._updateNonUniformScalingState(true);
  17406. }
  17407. else if (this.parent && this.parent._nonUniformScaling) {
  17408. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17409. }
  17410. else {
  17411. this._updateNonUniformScalingState(false);
  17412. }
  17413. this._afterComputeWorldMatrix();
  17414. // Absolute position
  17415. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17416. // Callbacks
  17417. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17418. if (!this._poseMatrix) {
  17419. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17420. }
  17421. // Cache the determinant
  17422. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17423. return this._worldMatrix;
  17424. };
  17425. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17426. };
  17427. /**
  17428. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17429. * @param func: callback function to add
  17430. *
  17431. * Returns the TransformNode.
  17432. */
  17433. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17434. this.onAfterWorldMatrixUpdateObservable.add(func);
  17435. return this;
  17436. };
  17437. /**
  17438. * Removes a registered callback function.
  17439. * Returns the TransformNode.
  17440. */
  17441. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17442. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17443. return this;
  17444. };
  17445. /**
  17446. * Clone the current transform node
  17447. * Returns the new transform node
  17448. * @param name Name of the new clone
  17449. * @param newParent New parent for the clone
  17450. * @param doNotCloneChildren Do not clone children hierarchy
  17451. */
  17452. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17453. var _this = this;
  17454. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17455. result.name = name;
  17456. result.id = name;
  17457. if (newParent) {
  17458. result.parent = newParent;
  17459. }
  17460. if (!doNotCloneChildren) {
  17461. // Children
  17462. var directDescendants = this.getDescendants(true);
  17463. for (var index = 0; index < directDescendants.length; index++) {
  17464. var child = directDescendants[index];
  17465. if (child.clone) {
  17466. child.clone(name + "." + child.name, result);
  17467. }
  17468. }
  17469. }
  17470. return result;
  17471. };
  17472. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17473. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17474. serializationObject.type = this.getClassName();
  17475. // Parent
  17476. if (this.parent) {
  17477. serializationObject.parentId = this.parent.id;
  17478. }
  17479. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17480. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17481. }
  17482. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17483. serializationObject.isEnabled = this.isEnabled();
  17484. // Parent
  17485. if (this.parent) {
  17486. serializationObject.parentId = this.parent.id;
  17487. }
  17488. return serializationObject;
  17489. };
  17490. // Statics
  17491. /**
  17492. * Returns a new TransformNode object parsed from the source provided.
  17493. * The parameter `parsedMesh` is the source.
  17494. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17495. */
  17496. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17497. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17498. if (BABYLON.Tags) {
  17499. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17500. }
  17501. if (parsedTransformNode.localMatrix) {
  17502. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17503. }
  17504. else if (parsedTransformNode.pivotMatrix) {
  17505. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17506. }
  17507. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17508. // Parent
  17509. if (parsedTransformNode.parentId) {
  17510. transformNode._waitingParentId = parsedTransformNode.parentId;
  17511. }
  17512. return transformNode;
  17513. };
  17514. /**
  17515. * Releases resources associated with this transform node.
  17516. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17517. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17518. */
  17519. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17520. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17521. // Animations
  17522. this.getScene().stopAnimation(this);
  17523. // Remove from scene
  17524. this.getScene().removeTransformNode(this);
  17525. this.onAfterWorldMatrixUpdateObservable.clear();
  17526. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17527. };
  17528. // Statics
  17529. TransformNode.BILLBOARDMODE_NONE = 0;
  17530. TransformNode.BILLBOARDMODE_X = 1;
  17531. TransformNode.BILLBOARDMODE_Y = 2;
  17532. TransformNode.BILLBOARDMODE_Z = 4;
  17533. TransformNode.BILLBOARDMODE_ALL = 7;
  17534. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17535. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17536. __decorate([
  17537. BABYLON.serializeAsVector3()
  17538. ], TransformNode.prototype, "_rotation", void 0);
  17539. __decorate([
  17540. BABYLON.serializeAsQuaternion()
  17541. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17542. __decorate([
  17543. BABYLON.serializeAsVector3()
  17544. ], TransformNode.prototype, "_scaling", void 0);
  17545. __decorate([
  17546. BABYLON.serialize()
  17547. ], TransformNode.prototype, "billboardMode", void 0);
  17548. __decorate([
  17549. BABYLON.serialize()
  17550. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17551. __decorate([
  17552. BABYLON.serialize()
  17553. ], TransformNode.prototype, "infiniteDistance", void 0);
  17554. __decorate([
  17555. BABYLON.serializeAsVector3()
  17556. ], TransformNode.prototype, "position", void 0);
  17557. return TransformNode;
  17558. }(BABYLON.Node));
  17559. BABYLON.TransformNode = TransformNode;
  17560. })(BABYLON || (BABYLON = {}));
  17561. //# sourceMappingURL=babylon.transformNode.js.map
  17562. "use strict";
  17563. var BABYLON;
  17564. (function (BABYLON) {
  17565. var AbstractMesh = /** @class */ (function (_super) {
  17566. __extends(AbstractMesh, _super);
  17567. // Constructor
  17568. function AbstractMesh(name, scene) {
  17569. if (scene === void 0) { scene = null; }
  17570. var _this = _super.call(this, name, scene, false) || this;
  17571. _this._facetNb = 0; // facet number
  17572. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17573. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17574. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17575. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17576. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17577. _this._subDiv = {
  17578. max: 1,
  17579. X: 1,
  17580. Y: 1,
  17581. Z: 1
  17582. };
  17583. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17584. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17585. // Events
  17586. /**
  17587. * An event triggered when this mesh collides with another one
  17588. * @type {BABYLON.Observable}
  17589. */
  17590. _this.onCollideObservable = new BABYLON.Observable();
  17591. /**
  17592. * An event triggered when the collision's position changes
  17593. * @type {BABYLON.Observable}
  17594. */
  17595. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17596. /**
  17597. * An event triggered when material is changed
  17598. * @type {BABYLON.Observable}
  17599. */
  17600. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17601. // Properties
  17602. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17603. /**
  17604. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17605. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17606. * or
  17607. * 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.
  17608. * for more info check WebGl documentations
  17609. */
  17610. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17611. /**
  17612. * 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:
  17613. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17614. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17615. * 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.
  17616. */
  17617. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17618. /**
  17619. * 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.
  17620. * The default value is -1 which means don't break the query and wait till the result.
  17621. */
  17622. _this.occlusionRetryCount = -1;
  17623. _this._occlusionInternalRetryCounter = 0;
  17624. _this._isOccluded = false;
  17625. _this._isOcclusionQueryInProgress = false;
  17626. _this._visibility = 1.0;
  17627. _this.alphaIndex = Number.MAX_VALUE;
  17628. _this.isVisible = true;
  17629. _this.isPickable = true;
  17630. _this.showBoundingBox = false;
  17631. _this.showSubMeshesBoundingBox = false;
  17632. _this.isBlocker = false;
  17633. _this.enablePointerMoveEvents = false;
  17634. _this.renderingGroupId = 0;
  17635. _this._receiveShadows = false;
  17636. _this.renderOutline = false;
  17637. _this.outlineColor = BABYLON.Color3.Red();
  17638. _this.outlineWidth = 0.02;
  17639. _this.renderOverlay = false;
  17640. _this.overlayColor = BABYLON.Color3.Red();
  17641. _this.overlayAlpha = 0.5;
  17642. _this._hasVertexAlpha = false;
  17643. _this._useVertexColors = true;
  17644. _this._computeBonesUsingShaders = true;
  17645. _this._numBoneInfluencers = 4;
  17646. _this._applyFog = true;
  17647. _this.useOctreeForRenderingSelection = true;
  17648. _this.useOctreeForPicking = true;
  17649. _this.useOctreeForCollisions = true;
  17650. _this._layerMask = 0x0FFFFFFF;
  17651. /**
  17652. * True if the mesh must be rendered in any case.
  17653. */
  17654. _this.alwaysSelectAsActiveMesh = false;
  17655. /**
  17656. * This scene's action manager
  17657. * @type {BABYLON.ActionManager}
  17658. */
  17659. _this.actionManager = null;
  17660. // Physics
  17661. _this.physicsImpostor = null;
  17662. // Collisions
  17663. _this._checkCollisions = false;
  17664. _this._collisionMask = -1;
  17665. _this._collisionGroup = -1;
  17666. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17667. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17668. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17669. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17670. // Edges
  17671. _this.edgesWidth = 1;
  17672. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17673. // Cache
  17674. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17675. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17676. _this._renderId = 0;
  17677. _this._intersectionsInProgress = new Array();
  17678. _this._unIndexed = false;
  17679. _this._lightSources = new Array();
  17680. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17681. if (collidedMesh === void 0) { collidedMesh = null; }
  17682. //TODO move this to the collision coordinator!
  17683. if (_this.getScene().workerCollisions)
  17684. newPosition.multiplyInPlace(_this._collider._radius);
  17685. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17686. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17687. _this.position.addInPlace(_this._diffPositionForCollisions);
  17688. }
  17689. if (collidedMesh) {
  17690. _this.onCollideObservable.notifyObservers(collidedMesh);
  17691. }
  17692. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17693. };
  17694. _this.getScene().addMesh(_this);
  17695. _this._resyncLightSources();
  17696. return _this;
  17697. }
  17698. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17699. get: function () {
  17700. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17706. get: function () {
  17707. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17713. get: function () {
  17714. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17720. get: function () {
  17721. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17727. get: function () {
  17728. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17729. },
  17730. enumerable: true,
  17731. configurable: true
  17732. });
  17733. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17734. /**
  17735. * Read-only : the number of facets in the mesh
  17736. */
  17737. get: function () {
  17738. return this._facetNb;
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17744. /**
  17745. * The number (integer) of subdivisions per axis in the partioning space
  17746. */
  17747. get: function () {
  17748. return this._partitioningSubdivisions;
  17749. },
  17750. set: function (nb) {
  17751. this._partitioningSubdivisions = nb;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17757. /**
  17758. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17759. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17760. */
  17761. get: function () {
  17762. return this._partitioningBBoxRatio;
  17763. },
  17764. set: function (ratio) {
  17765. this._partitioningBBoxRatio = ratio;
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17771. /**
  17772. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17773. * Works only for updatable meshes.
  17774. * Doesn't work with multi-materials.
  17775. */
  17776. get: function () {
  17777. return this._facetDepthSort;
  17778. },
  17779. set: function (sort) {
  17780. this._facetDepthSort = sort;
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17786. /**
  17787. * The location (Vector3) where the facet depth sort must be computed from.
  17788. * By default, the active camera position.
  17789. * Used only when facet depth sort is enabled.
  17790. */
  17791. get: function () {
  17792. return this._facetDepthSortFrom;
  17793. },
  17794. set: function (location) {
  17795. this._facetDepthSortFrom = location;
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17801. /**
  17802. * Read-only boolean : is the feature facetData enabled ?
  17803. */
  17804. get: function () {
  17805. return this._facetDataEnabled;
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17811. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17812. return false;
  17813. }
  17814. this._markSubMeshesAsMiscDirty();
  17815. return true;
  17816. };
  17817. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17818. set: function (callback) {
  17819. if (this._onCollideObserver) {
  17820. this.onCollideObservable.remove(this._onCollideObserver);
  17821. }
  17822. this._onCollideObserver = this.onCollideObservable.add(callback);
  17823. },
  17824. enumerable: true,
  17825. configurable: true
  17826. });
  17827. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17828. set: function (callback) {
  17829. if (this._onCollisionPositionChangeObserver) {
  17830. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17831. }
  17832. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17833. },
  17834. enumerable: true,
  17835. configurable: true
  17836. });
  17837. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17838. /**
  17839. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17840. */
  17841. get: function () {
  17842. return this._isOccluded;
  17843. },
  17844. set: function (value) {
  17845. this._isOccluded = value;
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17851. /**
  17852. * Flag to check the progress status of the query
  17853. */
  17854. get: function () {
  17855. return this._isOcclusionQueryInProgress;
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17861. /**
  17862. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17863. */
  17864. get: function () {
  17865. return this._visibility;
  17866. },
  17867. /**
  17868. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17869. */
  17870. set: function (value) {
  17871. if (this._visibility === value) {
  17872. return;
  17873. }
  17874. this._visibility = value;
  17875. this._markSubMeshesAsMiscDirty();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(AbstractMesh.prototype, "material", {
  17881. get: function () {
  17882. return this._material;
  17883. },
  17884. set: function (value) {
  17885. if (this._material === value) {
  17886. return;
  17887. }
  17888. this._material = value;
  17889. if (this.onMaterialChangedObservable.hasObservers) {
  17890. this.onMaterialChangedObservable.notifyObservers(this);
  17891. }
  17892. if (!this.subMeshes) {
  17893. return;
  17894. }
  17895. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17896. var subMesh = _a[_i];
  17897. subMesh.setEffect(null);
  17898. }
  17899. },
  17900. enumerable: true,
  17901. configurable: true
  17902. });
  17903. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17904. get: function () {
  17905. return this._receiveShadows;
  17906. },
  17907. set: function (value) {
  17908. if (this._receiveShadows === value) {
  17909. return;
  17910. }
  17911. this._receiveShadows = value;
  17912. this._markSubMeshesAsLightDirty();
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17918. get: function () {
  17919. return this._hasVertexAlpha;
  17920. },
  17921. set: function (value) {
  17922. if (this._hasVertexAlpha === value) {
  17923. return;
  17924. }
  17925. this._hasVertexAlpha = value;
  17926. this._markSubMeshesAsAttributesDirty();
  17927. this._markSubMeshesAsMiscDirty();
  17928. },
  17929. enumerable: true,
  17930. configurable: true
  17931. });
  17932. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17933. get: function () {
  17934. return this._useVertexColors;
  17935. },
  17936. set: function (value) {
  17937. if (this._useVertexColors === value) {
  17938. return;
  17939. }
  17940. this._useVertexColors = value;
  17941. this._markSubMeshesAsAttributesDirty();
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17947. get: function () {
  17948. return this._computeBonesUsingShaders;
  17949. },
  17950. set: function (value) {
  17951. if (this._computeBonesUsingShaders === value) {
  17952. return;
  17953. }
  17954. this._computeBonesUsingShaders = value;
  17955. this._markSubMeshesAsAttributesDirty();
  17956. },
  17957. enumerable: true,
  17958. configurable: true
  17959. });
  17960. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17961. get: function () {
  17962. return this._numBoneInfluencers;
  17963. },
  17964. set: function (value) {
  17965. if (this._numBoneInfluencers === value) {
  17966. return;
  17967. }
  17968. this._numBoneInfluencers = value;
  17969. this._markSubMeshesAsAttributesDirty();
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17975. get: function () {
  17976. return this._applyFog;
  17977. },
  17978. set: function (value) {
  17979. if (this._applyFog === value) {
  17980. return;
  17981. }
  17982. this._applyFog = value;
  17983. this._markSubMeshesAsMiscDirty();
  17984. },
  17985. enumerable: true,
  17986. configurable: true
  17987. });
  17988. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17989. get: function () {
  17990. return this._layerMask;
  17991. },
  17992. set: function (value) {
  17993. if (value === this._layerMask) {
  17994. return;
  17995. }
  17996. this._layerMask = value;
  17997. this._resyncLightSources();
  17998. },
  17999. enumerable: true,
  18000. configurable: true
  18001. });
  18002. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  18003. get: function () {
  18004. return this._collisionMask;
  18005. },
  18006. set: function (mask) {
  18007. this._collisionMask = !isNaN(mask) ? mask : -1;
  18008. },
  18009. enumerable: true,
  18010. configurable: true
  18011. });
  18012. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  18013. get: function () {
  18014. return this._collisionGroup;
  18015. },
  18016. set: function (mask) {
  18017. this._collisionGroup = !isNaN(mask) ? mask : -1;
  18018. },
  18019. enumerable: true,
  18020. configurable: true
  18021. });
  18022. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  18023. get: function () {
  18024. return null;
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  18030. get: function () {
  18031. return this._skeleton;
  18032. },
  18033. set: function (value) {
  18034. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  18035. this._skeleton._unregisterMeshWithPoseMatrix(this);
  18036. }
  18037. if (value && value.needInitialSkinMatrix) {
  18038. value._registerMeshWithPoseMatrix(this);
  18039. }
  18040. this._skeleton = value;
  18041. if (!this._skeleton) {
  18042. this._bonesTransformMatrices = null;
  18043. }
  18044. this._markSubMeshesAsAttributesDirty();
  18045. },
  18046. enumerable: true,
  18047. configurable: true
  18048. });
  18049. /**
  18050. * Returns the string "AbstractMesh"
  18051. */
  18052. AbstractMesh.prototype.getClassName = function () {
  18053. return "AbstractMesh";
  18054. };
  18055. /**
  18056. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18057. */
  18058. AbstractMesh.prototype.toString = function (fullDetails) {
  18059. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18060. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18061. if (this._skeleton) {
  18062. ret += ", skeleton: " + this._skeleton.name;
  18063. }
  18064. if (fullDetails) {
  18065. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18066. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18067. }
  18068. return ret;
  18069. };
  18070. AbstractMesh.prototype._rebuild = function () {
  18071. if (this._occlusionQuery) {
  18072. this._occlusionQuery = null;
  18073. }
  18074. if (this._edgesRenderer) {
  18075. this._edgesRenderer._rebuild();
  18076. }
  18077. if (!this.subMeshes) {
  18078. return;
  18079. }
  18080. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18081. var subMesh = _a[_i];
  18082. subMesh._rebuild();
  18083. }
  18084. };
  18085. AbstractMesh.prototype._resyncLightSources = function () {
  18086. this._lightSources.length = 0;
  18087. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18088. var light = _a[_i];
  18089. if (!light.isEnabled()) {
  18090. continue;
  18091. }
  18092. if (light.canAffectMesh(this)) {
  18093. this._lightSources.push(light);
  18094. }
  18095. }
  18096. this._markSubMeshesAsLightDirty();
  18097. };
  18098. AbstractMesh.prototype._resyncLighSource = function (light) {
  18099. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18100. var index = this._lightSources.indexOf(light);
  18101. if (index === -1) {
  18102. if (!isIn) {
  18103. return;
  18104. }
  18105. this._lightSources.push(light);
  18106. }
  18107. else {
  18108. if (isIn) {
  18109. return;
  18110. }
  18111. this._lightSources.splice(index, 1);
  18112. }
  18113. this._markSubMeshesAsLightDirty();
  18114. };
  18115. AbstractMesh.prototype._removeLightSource = function (light) {
  18116. var index = this._lightSources.indexOf(light);
  18117. if (index === -1) {
  18118. return;
  18119. }
  18120. this._lightSources.splice(index, 1);
  18121. this._markSubMeshesAsLightDirty();
  18122. };
  18123. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18124. if (!this.subMeshes) {
  18125. return;
  18126. }
  18127. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18128. var subMesh = _a[_i];
  18129. if (subMesh._materialDefines) {
  18130. func(subMesh._materialDefines);
  18131. }
  18132. }
  18133. };
  18134. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18135. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18136. };
  18137. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18138. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18139. };
  18140. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18141. if (!this.subMeshes) {
  18142. return;
  18143. }
  18144. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18145. var subMesh = _a[_i];
  18146. var material = subMesh.getMaterial();
  18147. if (material) {
  18148. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18149. }
  18150. }
  18151. };
  18152. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18153. /**
  18154. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18155. * Default : (1.0, 1.0, 1.0)
  18156. */
  18157. get: function () {
  18158. return this._scaling;
  18159. },
  18160. /**
  18161. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18162. * Default : (1.0, 1.0, 1.0)
  18163. */
  18164. set: function (newScaling) {
  18165. this._scaling = newScaling;
  18166. if (this.physicsImpostor) {
  18167. this.physicsImpostor.forceUpdate();
  18168. }
  18169. },
  18170. enumerable: true,
  18171. configurable: true
  18172. });
  18173. // Methods
  18174. /**
  18175. * Disables the mesh edger rendering mode.
  18176. * Returns the AbstractMesh.
  18177. */
  18178. AbstractMesh.prototype.disableEdgesRendering = function () {
  18179. if (this._edgesRenderer) {
  18180. this._edgesRenderer.dispose();
  18181. this._edgesRenderer = null;
  18182. }
  18183. return this;
  18184. };
  18185. /**
  18186. * Enables the edge rendering mode on the mesh.
  18187. * This mode makes the mesh edges visible.
  18188. * Returns the AbstractMesh.
  18189. */
  18190. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18191. if (epsilon === void 0) { epsilon = 0.95; }
  18192. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18193. this.disableEdgesRendering();
  18194. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18195. return this;
  18196. };
  18197. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18198. /**
  18199. * Returns true if the mesh is blocked. Used by the class Mesh.
  18200. * Returns the boolean `false` by default.
  18201. */
  18202. get: function () {
  18203. return false;
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. /**
  18209. * Returns the mesh itself by default, used by the class Mesh.
  18210. * Returned type : AbstractMesh
  18211. */
  18212. AbstractMesh.prototype.getLOD = function (camera) {
  18213. return this;
  18214. };
  18215. /**
  18216. * Returns 0 by default, used by the class Mesh.
  18217. * Returns an integer.
  18218. */
  18219. AbstractMesh.prototype.getTotalVertices = function () {
  18220. return 0;
  18221. };
  18222. /**
  18223. * Returns null by default, used by the class Mesh.
  18224. * Returned type : integer array
  18225. */
  18226. AbstractMesh.prototype.getIndices = function () {
  18227. return null;
  18228. };
  18229. /**
  18230. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18231. * Returned type : float array or Float32Array
  18232. */
  18233. AbstractMesh.prototype.getVerticesData = function (kind) {
  18234. return null;
  18235. };
  18236. /**
  18237. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18238. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18239. * The `data` are either a numeric array either a Float32Array.
  18240. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18241. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  18242. * Note that a new underlying VertexBuffer object is created each call.
  18243. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18244. *
  18245. * Possible `kind` values :
  18246. * - BABYLON.VertexBuffer.PositionKind
  18247. * - BABYLON.VertexBuffer.UVKind
  18248. * - BABYLON.VertexBuffer.UV2Kind
  18249. * - BABYLON.VertexBuffer.UV3Kind
  18250. * - BABYLON.VertexBuffer.UV4Kind
  18251. * - BABYLON.VertexBuffer.UV5Kind
  18252. * - BABYLON.VertexBuffer.UV6Kind
  18253. * - BABYLON.VertexBuffer.ColorKind
  18254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18258. *
  18259. * Returns the Mesh.
  18260. */
  18261. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18262. return this;
  18263. };
  18264. /**
  18265. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18266. * If the mesh has no geometry, it is simply returned as it is.
  18267. * The `data` are either a numeric array either a Float32Array.
  18268. * No new underlying VertexBuffer object is created.
  18269. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18270. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18271. *
  18272. * Possible `kind` values :
  18273. * - BABYLON.VertexBuffer.PositionKind
  18274. * - BABYLON.VertexBuffer.UVKind
  18275. * - BABYLON.VertexBuffer.UV2Kind
  18276. * - BABYLON.VertexBuffer.UV3Kind
  18277. * - BABYLON.VertexBuffer.UV4Kind
  18278. * - BABYLON.VertexBuffer.UV5Kind
  18279. * - BABYLON.VertexBuffer.UV6Kind
  18280. * - BABYLON.VertexBuffer.ColorKind
  18281. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18282. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18283. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18284. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18285. *
  18286. * Returns the Mesh.
  18287. */
  18288. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18289. return this;
  18290. };
  18291. /**
  18292. * Sets the mesh indices.
  18293. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18294. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18295. * This method creates a new index buffer each call.
  18296. * Returns the Mesh.
  18297. */
  18298. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18299. return this;
  18300. };
  18301. /** Returns false by default, used by the class Mesh.
  18302. * Returns a boolean
  18303. */
  18304. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18305. return false;
  18306. };
  18307. /**
  18308. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18309. * Returns a BoundingInfo
  18310. */
  18311. AbstractMesh.prototype.getBoundingInfo = function () {
  18312. if (this._masterMesh) {
  18313. return this._masterMesh.getBoundingInfo();
  18314. }
  18315. if (!this._boundingInfo) {
  18316. // this._boundingInfo is being created here
  18317. this._updateBoundingInfo();
  18318. }
  18319. // cannot be null.
  18320. return this._boundingInfo;
  18321. };
  18322. /**
  18323. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18324. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18325. */
  18326. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18327. if (includeDescendants === void 0) { includeDescendants = true; }
  18328. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18329. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18330. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18331. if (maxDimension === 0) {
  18332. return this;
  18333. }
  18334. var scale = 1 / maxDimension;
  18335. this.scaling.scaleInPlace(scale);
  18336. return this;
  18337. };
  18338. /**
  18339. * Sets a mesh new object BoundingInfo.
  18340. * Returns the AbstractMesh.
  18341. */
  18342. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18343. this._boundingInfo = boundingInfo;
  18344. return this;
  18345. };
  18346. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18347. get: function () {
  18348. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18349. },
  18350. enumerable: true,
  18351. configurable: true
  18352. });
  18353. AbstractMesh.prototype._preActivate = function () {
  18354. };
  18355. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18356. };
  18357. AbstractMesh.prototype._activate = function (renderId) {
  18358. this._renderId = renderId;
  18359. };
  18360. /**
  18361. * Returns the latest update of the World matrix
  18362. * Returns a Matrix.
  18363. */
  18364. AbstractMesh.prototype.getWorldMatrix = function () {
  18365. if (this._masterMesh) {
  18366. return this._masterMesh.getWorldMatrix();
  18367. }
  18368. return _super.prototype.getWorldMatrix.call(this);
  18369. };
  18370. /**
  18371. * Returns the latest update of the World matrix determinant.
  18372. */
  18373. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18374. if (this._masterMesh) {
  18375. return this._masterMesh._getWorldMatrixDeterminant();
  18376. }
  18377. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18378. };
  18379. // ================================== Point of View Movement =================================
  18380. /**
  18381. * Perform relative position change from the point of view of behind the front of the mesh.
  18382. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18383. * Supports definition of mesh facing forward or backward.
  18384. * @param {number} amountRight
  18385. * @param {number} amountUp
  18386. * @param {number} amountForward
  18387. *
  18388. * Returns the AbstractMesh.
  18389. */
  18390. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18391. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18392. return this;
  18393. };
  18394. /**
  18395. * Calculate relative position change from the point of view of behind the front of the mesh.
  18396. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18397. * Supports definition of mesh facing forward or backward.
  18398. * @param {number} amountRight
  18399. * @param {number} amountUp
  18400. * @param {number} amountForward
  18401. *
  18402. * Returns a new Vector3.
  18403. */
  18404. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18405. var rotMatrix = new BABYLON.Matrix();
  18406. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18407. rotQuaternion.toRotationMatrix(rotMatrix);
  18408. var translationDelta = BABYLON.Vector3.Zero();
  18409. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18410. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18411. return translationDelta;
  18412. };
  18413. // ================================== Point of View Rotation =================================
  18414. /**
  18415. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18416. * Supports definition of mesh facing forward or backward.
  18417. * @param {number} flipBack
  18418. * @param {number} twirlClockwise
  18419. * @param {number} tiltRight
  18420. *
  18421. * Returns the AbstractMesh.
  18422. */
  18423. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18424. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18425. return this;
  18426. };
  18427. /**
  18428. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18429. * Supports definition of mesh facing forward or backward.
  18430. * @param {number} flipBack
  18431. * @param {number} twirlClockwise
  18432. * @param {number} tiltRight
  18433. *
  18434. * Returns a new Vector3.
  18435. */
  18436. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18437. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18438. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18439. };
  18440. /**
  18441. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18442. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18443. */
  18444. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18445. if (includeDescendants === void 0) { includeDescendants = true; }
  18446. this.computeWorldMatrix(true);
  18447. var min;
  18448. var max;
  18449. var boundingInfo = this.getBoundingInfo();
  18450. if (!this.subMeshes) {
  18451. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18452. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18453. }
  18454. else {
  18455. min = boundingInfo.boundingBox.minimumWorld;
  18456. max = boundingInfo.boundingBox.maximumWorld;
  18457. }
  18458. if (includeDescendants) {
  18459. var descendants = this.getDescendants(false);
  18460. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18461. var descendant = descendants_1[_i];
  18462. var childMesh = descendant;
  18463. childMesh.computeWorldMatrix(true);
  18464. //make sure we have the needed params to get mix and max
  18465. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18466. continue;
  18467. }
  18468. var childBoundingInfo = childMesh.getBoundingInfo();
  18469. var boundingBox = childBoundingInfo.boundingBox;
  18470. var minBox = boundingBox.minimumWorld;
  18471. var maxBox = boundingBox.maximumWorld;
  18472. BABYLON.Tools.CheckExtends(minBox, min, max);
  18473. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18474. }
  18475. }
  18476. return {
  18477. min: min,
  18478. max: max
  18479. };
  18480. };
  18481. /**
  18482. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18483. * Returns the AbstractMesh.
  18484. */
  18485. AbstractMesh.prototype._updateBoundingInfo = function () {
  18486. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18487. this._boundingInfo.update(this.worldMatrixFromCache);
  18488. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18489. return this;
  18490. };
  18491. /**
  18492. * Update a mesh's children BoundingInfo objects only.
  18493. * Returns the AbstractMesh.
  18494. */
  18495. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18496. if (!this.subMeshes) {
  18497. return this;
  18498. }
  18499. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18500. var subMesh = this.subMeshes[subIndex];
  18501. if (!subMesh.IsGlobal) {
  18502. subMesh.updateBoundingInfo(matrix);
  18503. }
  18504. }
  18505. return this;
  18506. };
  18507. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18508. // Bounding info
  18509. this._updateBoundingInfo();
  18510. };
  18511. /**
  18512. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18513. * A mesh is in the frustum if its bounding box intersects the frustum.
  18514. * Boolean returned.
  18515. */
  18516. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18517. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18518. };
  18519. /**
  18520. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18521. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18522. * Boolean returned.
  18523. */
  18524. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18525. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18526. ;
  18527. };
  18528. /**
  18529. * True if the mesh intersects another mesh or a SolidParticle object.
  18530. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  18531. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18532. * Returns a boolean.
  18533. */
  18534. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18535. if (precise === void 0) { precise = false; }
  18536. if (!this._boundingInfo || !mesh._boundingInfo) {
  18537. return false;
  18538. }
  18539. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18540. return true;
  18541. }
  18542. if (includeDescendants) {
  18543. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18544. var child = _a[_i];
  18545. if (child.intersectsMesh(mesh, precise, true)) {
  18546. return true;
  18547. }
  18548. }
  18549. }
  18550. return false;
  18551. };
  18552. /**
  18553. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18554. * Returns a boolean.
  18555. */
  18556. AbstractMesh.prototype.intersectsPoint = function (point) {
  18557. if (!this._boundingInfo) {
  18558. return false;
  18559. }
  18560. return this._boundingInfo.intersectsPoint(point);
  18561. };
  18562. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18563. return this.physicsImpostor;
  18564. };
  18565. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18566. if (camera === void 0) { camera = null; }
  18567. if (!camera) {
  18568. camera = this.getScene().activeCamera;
  18569. }
  18570. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18571. };
  18572. /**
  18573. * Returns the distance from the mesh to the active camera.
  18574. * Returns a float.
  18575. */
  18576. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18577. if (camera === void 0) { camera = null; }
  18578. if (!camera) {
  18579. camera = this.getScene().activeCamera;
  18580. }
  18581. return this.absolutePosition.subtract(camera.position).length();
  18582. };
  18583. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18584. if (!this.physicsImpostor) {
  18585. return this;
  18586. }
  18587. this.physicsImpostor.applyImpulse(force, contactPoint);
  18588. return this;
  18589. };
  18590. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18591. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18592. return this;
  18593. }
  18594. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18595. mainPivot: pivot1,
  18596. connectedPivot: pivot2,
  18597. nativeParams: options
  18598. });
  18599. return this;
  18600. };
  18601. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18602. // Collisions
  18603. /**
  18604. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18605. * Default `false`.
  18606. */
  18607. get: function () {
  18608. return this._checkCollisions;
  18609. },
  18610. set: function (collisionEnabled) {
  18611. this._checkCollisions = collisionEnabled;
  18612. if (this.getScene().workerCollisions) {
  18613. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18614. }
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18620. /**
  18621. * Gets Collider object used to compute collisions (not physics)
  18622. */
  18623. get: function () {
  18624. return this._collider;
  18625. },
  18626. enumerable: true,
  18627. configurable: true
  18628. });
  18629. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18630. var globalPosition = this.getAbsolutePosition();
  18631. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18632. if (!this._collider) {
  18633. this._collider = new BABYLON.Collider();
  18634. }
  18635. this._collider._radius = this.ellipsoid;
  18636. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18637. return this;
  18638. };
  18639. // Submeshes octree
  18640. /**
  18641. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18642. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18643. * Returns an Octree of submeshes.
  18644. */
  18645. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18646. if (maxCapacity === void 0) { maxCapacity = 64; }
  18647. if (maxDepth === void 0) { maxDepth = 2; }
  18648. if (!this._submeshesOctree) {
  18649. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18650. }
  18651. this.computeWorldMatrix(true);
  18652. var boundingInfo = this.getBoundingInfo();
  18653. // Update octree
  18654. var bbox = boundingInfo.boundingBox;
  18655. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18656. return this._submeshesOctree;
  18657. };
  18658. // Collisions
  18659. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18660. this._generatePointsArray();
  18661. if (!this._positions) {
  18662. return this;
  18663. }
  18664. // Transformation
  18665. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18666. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18667. subMesh._lastColliderWorldVertices = [];
  18668. subMesh._trianglePlanes = [];
  18669. var start = subMesh.verticesStart;
  18670. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18671. for (var i = start; i < end; i++) {
  18672. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18673. }
  18674. }
  18675. // Collide
  18676. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18677. if (collider.collisionFound) {
  18678. collider.collidedMesh = this;
  18679. }
  18680. return this;
  18681. };
  18682. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18683. var subMeshes;
  18684. var len;
  18685. // Octrees
  18686. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18687. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18688. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18689. len = intersections.length;
  18690. subMeshes = intersections.data;
  18691. }
  18692. else {
  18693. subMeshes = this.subMeshes;
  18694. len = subMeshes.length;
  18695. }
  18696. for (var index = 0; index < len; index++) {
  18697. var subMesh = subMeshes[index];
  18698. // Bounding test
  18699. if (len > 1 && !subMesh._checkCollision(collider))
  18700. continue;
  18701. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18702. }
  18703. return this;
  18704. };
  18705. AbstractMesh.prototype._checkCollision = function (collider) {
  18706. // Bounding box test
  18707. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18708. return this;
  18709. // Transformation matrix
  18710. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18711. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18712. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18713. return this;
  18714. };
  18715. // Picking
  18716. AbstractMesh.prototype._generatePointsArray = function () {
  18717. return false;
  18718. };
  18719. /**
  18720. * Checks if the passed Ray intersects with the mesh.
  18721. * Returns an object PickingInfo.
  18722. */
  18723. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18724. var pickingInfo = new BABYLON.PickingInfo();
  18725. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18726. return pickingInfo;
  18727. }
  18728. if (!this._generatePointsArray()) {
  18729. return pickingInfo;
  18730. }
  18731. var intersectInfo = null;
  18732. // Octrees
  18733. var subMeshes;
  18734. var len;
  18735. if (this._submeshesOctree && this.useOctreeForPicking) {
  18736. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18737. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18738. len = intersections.length;
  18739. subMeshes = intersections.data;
  18740. }
  18741. else {
  18742. subMeshes = this.subMeshes;
  18743. len = subMeshes.length;
  18744. }
  18745. for (var index = 0; index < len; index++) {
  18746. var subMesh = subMeshes[index];
  18747. // Bounding test
  18748. if (len > 1 && !subMesh.canIntersects(ray))
  18749. continue;
  18750. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18751. if (currentIntersectInfo) {
  18752. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18753. intersectInfo = currentIntersectInfo;
  18754. intersectInfo.subMeshId = index;
  18755. if (fastCheck) {
  18756. break;
  18757. }
  18758. }
  18759. }
  18760. }
  18761. if (intersectInfo) {
  18762. // Get picked point
  18763. var world = this.getWorldMatrix();
  18764. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18765. var direction = ray.direction.clone();
  18766. direction = direction.scale(intersectInfo.distance);
  18767. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18768. var pickedPoint = worldOrigin.add(worldDirection);
  18769. // Return result
  18770. pickingInfo.hit = true;
  18771. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18772. pickingInfo.pickedPoint = pickedPoint;
  18773. pickingInfo.pickedMesh = this;
  18774. pickingInfo.bu = intersectInfo.bu || 0;
  18775. pickingInfo.bv = intersectInfo.bv || 0;
  18776. pickingInfo.faceId = intersectInfo.faceId;
  18777. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18778. return pickingInfo;
  18779. }
  18780. return pickingInfo;
  18781. };
  18782. /**
  18783. * Clones the mesh, used by the class Mesh.
  18784. * Just returns `null` for an AbstractMesh.
  18785. */
  18786. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18787. return null;
  18788. };
  18789. /**
  18790. * Disposes all the mesh submeshes.
  18791. * Returns the AbstractMesh.
  18792. */
  18793. AbstractMesh.prototype.releaseSubMeshes = function () {
  18794. if (this.subMeshes) {
  18795. while (this.subMeshes.length) {
  18796. this.subMeshes[0].dispose();
  18797. }
  18798. }
  18799. else {
  18800. this.subMeshes = new Array();
  18801. }
  18802. return this;
  18803. };
  18804. /**
  18805. * Releases resources associated with this abstract mesh.
  18806. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18807. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18808. */
  18809. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18810. var _this = this;
  18811. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18812. var index;
  18813. // Smart Array Retainers.
  18814. this.getScene().freeActiveMeshes();
  18815. this.getScene().freeRenderingGroups();
  18816. // Action manager
  18817. if (this.actionManager !== undefined && this.actionManager !== null) {
  18818. this.actionManager.dispose();
  18819. this.actionManager = null;
  18820. }
  18821. // Skeleton
  18822. this._skeleton = null;
  18823. // Physics
  18824. if (this.physicsImpostor) {
  18825. this.physicsImpostor.dispose();
  18826. }
  18827. // Intersections in progress
  18828. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18829. var other = this._intersectionsInProgress[index];
  18830. var pos = other._intersectionsInProgress.indexOf(this);
  18831. other._intersectionsInProgress.splice(pos, 1);
  18832. }
  18833. this._intersectionsInProgress = [];
  18834. // Lights
  18835. var lights = this.getScene().lights;
  18836. lights.forEach(function (light) {
  18837. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18838. if (meshIndex !== -1) {
  18839. light.includedOnlyMeshes.splice(meshIndex, 1);
  18840. }
  18841. meshIndex = light.excludedMeshes.indexOf(_this);
  18842. if (meshIndex !== -1) {
  18843. light.excludedMeshes.splice(meshIndex, 1);
  18844. }
  18845. // Shadow generators
  18846. var generator = light.getShadowGenerator();
  18847. if (generator) {
  18848. var shadowMap = generator.getShadowMap();
  18849. if (shadowMap && shadowMap.renderList) {
  18850. meshIndex = shadowMap.renderList.indexOf(_this);
  18851. if (meshIndex !== -1) {
  18852. shadowMap.renderList.splice(meshIndex, 1);
  18853. }
  18854. }
  18855. }
  18856. });
  18857. // Edges
  18858. if (this._edgesRenderer) {
  18859. this._edgesRenderer.dispose();
  18860. this._edgesRenderer = null;
  18861. }
  18862. // SubMeshes
  18863. if (this.getClassName() !== "InstancedMesh") {
  18864. this.releaseSubMeshes();
  18865. }
  18866. // Octree
  18867. var sceneOctree = this.getScene().selectionOctree;
  18868. if (sceneOctree !== undefined && sceneOctree !== null) {
  18869. var index = sceneOctree.dynamicContent.indexOf(this);
  18870. if (index !== -1) {
  18871. sceneOctree.dynamicContent.splice(index, 1);
  18872. }
  18873. }
  18874. // Query
  18875. var engine = this.getScene().getEngine();
  18876. if (this._occlusionQuery) {
  18877. this._isOcclusionQueryInProgress = false;
  18878. engine.deleteQuery(this._occlusionQuery);
  18879. this._occlusionQuery = null;
  18880. }
  18881. // Engine
  18882. engine.wipeCaches();
  18883. // Remove from scene
  18884. this.getScene().removeMesh(this);
  18885. if (disposeMaterialAndTextures) {
  18886. if (this.material) {
  18887. this.material.dispose(false, true);
  18888. }
  18889. }
  18890. if (!doNotRecurse) {
  18891. // Particles
  18892. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18893. if (this.getScene().particleSystems[index].emitter === this) {
  18894. this.getScene().particleSystems[index].dispose();
  18895. index--;
  18896. }
  18897. }
  18898. }
  18899. // facet data
  18900. if (this._facetDataEnabled) {
  18901. this.disableFacetData();
  18902. }
  18903. this.onAfterWorldMatrixUpdateObservable.clear();
  18904. this.onCollideObservable.clear();
  18905. this.onCollisionPositionChangeObservable.clear();
  18906. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18907. };
  18908. /**
  18909. * Adds the passed mesh as a child to the current mesh.
  18910. * Returns the AbstractMesh.
  18911. */
  18912. AbstractMesh.prototype.addChild = function (mesh) {
  18913. mesh.setParent(this);
  18914. return this;
  18915. };
  18916. /**
  18917. * Removes the passed mesh from the current mesh children list.
  18918. * Returns the AbstractMesh.
  18919. */
  18920. AbstractMesh.prototype.removeChild = function (mesh) {
  18921. mesh.setParent(null);
  18922. return this;
  18923. };
  18924. // Facet data
  18925. /**
  18926. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18927. * Returns the AbstractMesh.
  18928. */
  18929. AbstractMesh.prototype._initFacetData = function () {
  18930. if (!this._facetNormals) {
  18931. this._facetNormals = new Array();
  18932. }
  18933. if (!this._facetPositions) {
  18934. this._facetPositions = new Array();
  18935. }
  18936. if (!this._facetPartitioning) {
  18937. this._facetPartitioning = new Array();
  18938. }
  18939. this._facetNb = (this.getIndices().length / 3) | 0;
  18940. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18941. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18942. for (var f = 0; f < this._facetNb; f++) {
  18943. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18944. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18945. }
  18946. this._facetDataEnabled = true;
  18947. return this;
  18948. };
  18949. /**
  18950. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18951. * This method can be called within the render loop.
  18952. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  18953. * Returns the AbstractMesh.
  18954. */
  18955. AbstractMesh.prototype.updateFacetData = function () {
  18956. if (!this._facetDataEnabled) {
  18957. this._initFacetData();
  18958. }
  18959. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18960. var indices = this.getIndices();
  18961. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18962. var bInfo = this.getBoundingInfo();
  18963. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18964. // init arrays, matrix and sort function on first call
  18965. this._facetDepthSortEnabled = true;
  18966. if (indices instanceof Uint16Array) {
  18967. this._depthSortedIndices = new Uint16Array(indices);
  18968. }
  18969. else if (indices instanceof Uint32Array) {
  18970. this._depthSortedIndices = new Uint32Array(indices);
  18971. }
  18972. else {
  18973. var needs32bits = false;
  18974. for (var i = 0; i < indices.length; i++) {
  18975. if (indices[i] > 65535) {
  18976. needs32bits = true;
  18977. break;
  18978. }
  18979. }
  18980. if (needs32bits) {
  18981. this._depthSortedIndices = new Uint32Array(indices);
  18982. }
  18983. else {
  18984. this._depthSortedIndices = new Uint16Array(indices);
  18985. }
  18986. }
  18987. this._facetDepthSortFunction = function (f1, f2) {
  18988. return (f2.sqDistance - f1.sqDistance);
  18989. };
  18990. if (!this._facetDepthSortFrom) {
  18991. var camera = this.getScene().activeCamera;
  18992. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18993. }
  18994. this._depthSortedFacets = [];
  18995. for (var f = 0; f < this._facetNb; f++) {
  18996. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18997. this._depthSortedFacets.push(depthSortedFacet);
  18998. }
  18999. this._invertedMatrix = BABYLON.Matrix.Identity();
  19000. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  19001. }
  19002. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  19003. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  19004. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  19005. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  19006. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  19007. this._subDiv.max = this._partitioningSubdivisions;
  19008. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  19009. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  19010. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  19011. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  19012. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  19013. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  19014. // set the parameters for ComputeNormals()
  19015. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  19016. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  19017. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  19018. this._facetParameters.bInfo = bInfo;
  19019. this._facetParameters.bbSize = this._bbSize;
  19020. this._facetParameters.subDiv = this._subDiv;
  19021. this._facetParameters.ratio = this.partitioningBBoxRatio;
  19022. this._facetParameters.depthSort = this._facetDepthSort;
  19023. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19024. this.computeWorldMatrix(true);
  19025. this._worldMatrix.invertToRef(this._invertedMatrix);
  19026. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  19027. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  19028. }
  19029. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  19030. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  19031. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19032. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  19033. var l = (this._depthSortedIndices.length / 3) | 0;
  19034. for (var f = 0; f < l; f++) {
  19035. var sind = this._depthSortedFacets[f].ind;
  19036. this._depthSortedIndices[f * 3] = indices[sind];
  19037. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  19038. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  19039. }
  19040. this.updateIndices(this._depthSortedIndices);
  19041. }
  19042. return this;
  19043. };
  19044. /**
  19045. * Returns the facetLocalNormals array.
  19046. * The normals are expressed in the mesh local space.
  19047. */
  19048. AbstractMesh.prototype.getFacetLocalNormals = function () {
  19049. if (!this._facetNormals) {
  19050. this.updateFacetData();
  19051. }
  19052. return this._facetNormals;
  19053. };
  19054. /**
  19055. * Returns the facetLocalPositions array.
  19056. * The facet positions are expressed in the mesh local space.
  19057. */
  19058. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19059. if (!this._facetPositions) {
  19060. this.updateFacetData();
  19061. }
  19062. return this._facetPositions;
  19063. };
  19064. /**
  19065. * Returns the facetLocalPartioning array.
  19066. */
  19067. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19068. if (!this._facetPartitioning) {
  19069. this.updateFacetData();
  19070. }
  19071. return this._facetPartitioning;
  19072. };
  19073. /**
  19074. * Returns the i-th facet position in the world system.
  19075. * This method allocates a new Vector3 per call.
  19076. */
  19077. AbstractMesh.prototype.getFacetPosition = function (i) {
  19078. var pos = BABYLON.Vector3.Zero();
  19079. this.getFacetPositionToRef(i, pos);
  19080. return pos;
  19081. };
  19082. /**
  19083. * Sets the reference Vector3 with the i-th facet position in the world system.
  19084. * Returns the AbstractMesh.
  19085. */
  19086. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19087. var localPos = (this.getFacetLocalPositions())[i];
  19088. var world = this.getWorldMatrix();
  19089. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19090. return this;
  19091. };
  19092. /**
  19093. * Returns the i-th facet normal in the world system.
  19094. * This method allocates a new Vector3 per call.
  19095. */
  19096. AbstractMesh.prototype.getFacetNormal = function (i) {
  19097. var norm = BABYLON.Vector3.Zero();
  19098. this.getFacetNormalToRef(i, norm);
  19099. return norm;
  19100. };
  19101. /**
  19102. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19103. * Returns the AbstractMesh.
  19104. */
  19105. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19106. var localNorm = (this.getFacetLocalNormals())[i];
  19107. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19108. return this;
  19109. };
  19110. /**
  19111. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  19112. */
  19113. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19114. var bInfo = this.getBoundingInfo();
  19115. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19116. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19117. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19118. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19119. return null;
  19120. }
  19121. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19122. };
  19123. /**
  19124. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19125. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19126. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  19127. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19128. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  19129. */
  19130. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19131. if (checkFace === void 0) { checkFace = false; }
  19132. if (facing === void 0) { facing = true; }
  19133. var world = this.getWorldMatrix();
  19134. var invMat = BABYLON.Tmp.Matrix[5];
  19135. world.invertToRef(invMat);
  19136. var invVect = BABYLON.Tmp.Vector3[8];
  19137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19138. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19139. if (projected) {
  19140. // tranform the local computed projected vector to world coordinates
  19141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19142. }
  19143. return closest;
  19144. };
  19145. /**
  19146. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19147. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19148. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  19149. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19150. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  19151. */
  19152. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19153. if (checkFace === void 0) { checkFace = false; }
  19154. if (facing === void 0) { facing = true; }
  19155. var closest = null;
  19156. var tmpx = 0.0;
  19157. var tmpy = 0.0;
  19158. var tmpz = 0.0;
  19159. var d = 0.0; // tmp dot facet normal * facet position
  19160. var t0 = 0.0;
  19161. var projx = 0.0;
  19162. var projy = 0.0;
  19163. var projz = 0.0;
  19164. // Get all the facets in the same partitioning block than (x, y, z)
  19165. var facetPositions = this.getFacetLocalPositions();
  19166. var facetNormals = this.getFacetLocalNormals();
  19167. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19168. if (!facetsInBlock) {
  19169. return null;
  19170. }
  19171. // Get the closest facet to (x, y, z)
  19172. var shortest = Number.MAX_VALUE; // init distance vars
  19173. var tmpDistance = shortest;
  19174. var fib; // current facet in the block
  19175. var norm; // current facet normal
  19176. var p0; // current facet barycenter position
  19177. // loop on all the facets in the current partitioning block
  19178. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19179. fib = facetsInBlock[idx];
  19180. norm = facetNormals[fib];
  19181. p0 = facetPositions[fib];
  19182. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19183. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19184. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19185. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19186. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19187. projx = x + norm.x * t0;
  19188. projy = y + norm.y * t0;
  19189. projz = z + norm.z * t0;
  19190. tmpx = projx - x;
  19191. tmpy = projy - y;
  19192. tmpz = projz - z;
  19193. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19194. if (tmpDistance < shortest) {
  19195. shortest = tmpDistance;
  19196. closest = fib;
  19197. if (projected) {
  19198. projected.x = projx;
  19199. projected.y = projy;
  19200. projected.z = projz;
  19201. }
  19202. }
  19203. }
  19204. }
  19205. return closest;
  19206. };
  19207. /**
  19208. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19209. */
  19210. AbstractMesh.prototype.getFacetDataParameters = function () {
  19211. return this._facetParameters;
  19212. };
  19213. /**
  19214. * Disables the feature FacetData and frees the related memory.
  19215. * Returns the AbstractMesh.
  19216. */
  19217. AbstractMesh.prototype.disableFacetData = function () {
  19218. if (this._facetDataEnabled) {
  19219. this._facetDataEnabled = false;
  19220. this._facetPositions = new Array();
  19221. this._facetNormals = new Array();
  19222. this._facetPartitioning = new Array();
  19223. this._facetParameters = null;
  19224. this._depthSortedIndices = new Uint32Array(0);
  19225. }
  19226. return this;
  19227. };
  19228. /**
  19229. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19230. * Returns the mesh.
  19231. */
  19232. AbstractMesh.prototype.updateIndices = function (indices) {
  19233. return this;
  19234. };
  19235. /**
  19236. * The mesh Geometry. Actually used by the Mesh object.
  19237. * Returns a blank geometry object.
  19238. */
  19239. /**
  19240. * Creates new normals data for the mesh.
  19241. * @param updatable.
  19242. */
  19243. AbstractMesh.prototype.createNormals = function (updatable) {
  19244. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19245. var indices = this.getIndices();
  19246. var normals;
  19247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19248. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19249. }
  19250. else {
  19251. normals = [];
  19252. }
  19253. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19254. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19255. };
  19256. /**
  19257. * Align the mesh with a normal.
  19258. * Returns the mesh.
  19259. */
  19260. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19261. if (!upDirection) {
  19262. upDirection = BABYLON.Axis.Y;
  19263. }
  19264. var axisX = BABYLON.Tmp.Vector3[0];
  19265. var axisZ = BABYLON.Tmp.Vector3[1];
  19266. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19267. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19268. if (this.rotationQuaternion) {
  19269. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19270. }
  19271. else {
  19272. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19273. }
  19274. return this;
  19275. };
  19276. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19277. var engine = this.getEngine();
  19278. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19279. this._isOccluded = false;
  19280. return;
  19281. }
  19282. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19283. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19284. if (isOcclusionQueryAvailable) {
  19285. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19286. this._isOcclusionQueryInProgress = false;
  19287. this._occlusionInternalRetryCounter = 0;
  19288. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19289. }
  19290. else {
  19291. this._occlusionInternalRetryCounter++;
  19292. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19293. this._isOcclusionQueryInProgress = false;
  19294. this._occlusionInternalRetryCounter = 0;
  19295. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19296. // if strict continue the last state of the object.
  19297. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19298. }
  19299. else {
  19300. return;
  19301. }
  19302. }
  19303. }
  19304. var scene = this.getScene();
  19305. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19306. if (!this._occlusionQuery) {
  19307. this._occlusionQuery = engine.createQuery();
  19308. }
  19309. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19310. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19311. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19312. this._isOcclusionQueryInProgress = true;
  19313. };
  19314. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19315. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19316. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19317. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19318. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19319. return AbstractMesh;
  19320. }(BABYLON.TransformNode));
  19321. BABYLON.AbstractMesh = AbstractMesh;
  19322. })(BABYLON || (BABYLON = {}));
  19323. //# sourceMappingURL=babylon.abstractMesh.js.map
  19324. "use strict";
  19325. var BABYLON;
  19326. (function (BABYLON) {
  19327. /**
  19328. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19329. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19330. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  19331. */
  19332. var Light = /** @class */ (function (_super) {
  19333. __extends(Light, _super);
  19334. /**
  19335. * Creates a Light object in the scene.
  19336. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19337. * @param name The firendly name of the light
  19338. * @param scene The scene the light belongs too
  19339. */
  19340. function Light(name, scene) {
  19341. var _this = _super.call(this, name, scene) || this;
  19342. /**
  19343. * Diffuse gives the basic color to an object.
  19344. */
  19345. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19346. /**
  19347. * Specular produces a highlight color on an object.
  19348. * Note: This is note affecting PBR materials.
  19349. */
  19350. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19351. /**
  19352. * Strength of the light.
  19353. * Note: By default it is define in the framework own unit.
  19354. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19355. */
  19356. _this.intensity = 1.0;
  19357. /**
  19358. * Defines how far from the source the light is impacting in scene units.
  19359. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19360. */
  19361. _this.range = Number.MAX_VALUE;
  19362. /**
  19363. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19364. * of light.
  19365. */
  19366. _this._photometricScale = 1.0;
  19367. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19368. _this._radius = 0.00001;
  19369. /**
  19370. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19371. * exceeding the number allowed of the materials.
  19372. */
  19373. _this.renderPriority = 0;
  19374. /**
  19375. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19376. * the current shadow generator.
  19377. */
  19378. _this.shadowEnabled = true;
  19379. _this._excludeWithLayerMask = 0;
  19380. _this._includeOnlyWithLayerMask = 0;
  19381. _this._lightmapMode = 0;
  19382. /**
  19383. * @ignore Internal use only.
  19384. */
  19385. _this._excludedMeshesIds = new Array();
  19386. /**
  19387. * @ignore Internal use only.
  19388. */
  19389. _this._includedOnlyMeshesIds = new Array();
  19390. _this.getScene().addLight(_this);
  19391. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19392. _this._buildUniformLayout();
  19393. _this.includedOnlyMeshes = new Array();
  19394. _this.excludedMeshes = new Array();
  19395. _this._resyncMeshes();
  19396. return _this;
  19397. }
  19398. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19399. /**
  19400. * If every light affecting the material is in this lightmapMode,
  19401. * material.lightmapTexture adds or multiplies
  19402. * (depends on material.useLightmapAsShadowmap)
  19403. * after every other light calculations.
  19404. */
  19405. get: function () {
  19406. return Light._LIGHTMAP_DEFAULT;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19412. /**
  19413. * material.lightmapTexture as only diffuse lighting from this light
  19414. * adds only specular lighting from this light
  19415. * adds dynamic shadows
  19416. */
  19417. get: function () {
  19418. return Light._LIGHTMAP_SPECULAR;
  19419. },
  19420. enumerable: true,
  19421. configurable: true
  19422. });
  19423. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19424. /**
  19425. * material.lightmapTexture as only lighting
  19426. * no light calculation from this light
  19427. * only adds dynamic shadows from this light
  19428. */
  19429. get: function () {
  19430. return Light._LIGHTMAP_SHADOWSONLY;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19436. /**
  19437. * Each light type uses the default quantity according to its type:
  19438. * point/spot lights use luminous intensity
  19439. * directional lights use illuminance
  19440. */
  19441. get: function () {
  19442. return Light._INTENSITYMODE_AUTOMATIC;
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19448. /**
  19449. * lumen (lm)
  19450. */
  19451. get: function () {
  19452. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19458. /**
  19459. * candela (lm/sr)
  19460. */
  19461. get: function () {
  19462. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19468. /**
  19469. * lux (lm/m^2)
  19470. */
  19471. get: function () {
  19472. return Light._INTENSITYMODE_ILLUMINANCE;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19478. /**
  19479. * nit (cd/m^2)
  19480. */
  19481. get: function () {
  19482. return Light._INTENSITYMODE_LUMINANCE;
  19483. },
  19484. enumerable: true,
  19485. configurable: true
  19486. });
  19487. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19488. /**
  19489. * Light type const id of the point light.
  19490. */
  19491. get: function () {
  19492. return Light._LIGHTTYPEID_POINTLIGHT;
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19498. /**
  19499. * Light type const id of the directional light.
  19500. */
  19501. get: function () {
  19502. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19508. /**
  19509. * Light type const id of the spot light.
  19510. */
  19511. get: function () {
  19512. return Light._LIGHTTYPEID_SPOTLIGHT;
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19518. /**
  19519. * Light type const id of the hemispheric light.
  19520. */
  19521. get: function () {
  19522. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(Light.prototype, "intensityMode", {
  19528. /**
  19529. * Gets the photometric scale used to interpret the intensity.
  19530. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19531. */
  19532. get: function () {
  19533. return this._intensityMode;
  19534. },
  19535. /**
  19536. * Sets the photometric scale used to interpret the intensity.
  19537. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19538. */
  19539. set: function (value) {
  19540. this._intensityMode = value;
  19541. this._computePhotometricScale();
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. ;
  19547. ;
  19548. Object.defineProperty(Light.prototype, "radius", {
  19549. /**
  19550. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19551. */
  19552. get: function () {
  19553. return this._radius;
  19554. },
  19555. /**
  19556. * sets the light radius used by PBR Materials to simulate soft area lights.
  19557. */
  19558. set: function (value) {
  19559. this._radius = value;
  19560. this._computePhotometricScale();
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. ;
  19566. ;
  19567. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19568. /**
  19569. * Gets the only meshes impacted by this light.
  19570. */
  19571. get: function () {
  19572. return this._includedOnlyMeshes;
  19573. },
  19574. /**
  19575. * Sets the only meshes impacted by this light.
  19576. */
  19577. set: function (value) {
  19578. this._includedOnlyMeshes = value;
  19579. this._hookArrayForIncludedOnly(value);
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19585. /**
  19586. * Gets the meshes not impacted by this light.
  19587. */
  19588. get: function () {
  19589. return this._excludedMeshes;
  19590. },
  19591. /**
  19592. * Sets the meshes not impacted by this light.
  19593. */
  19594. set: function (value) {
  19595. this._excludedMeshes = value;
  19596. this._hookArrayForExcluded(value);
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19602. /**
  19603. * Gets the layer id use to find what meshes are not impacted by the light.
  19604. * Inactive if 0
  19605. */
  19606. get: function () {
  19607. return this._excludeWithLayerMask;
  19608. },
  19609. /**
  19610. * Sets the layer id use to find what meshes are not impacted by the light.
  19611. * Inactive if 0
  19612. */
  19613. set: function (value) {
  19614. this._excludeWithLayerMask = value;
  19615. this._resyncMeshes();
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19621. /**
  19622. * Gets the layer id use to find what meshes are impacted by the light.
  19623. * Inactive if 0
  19624. */
  19625. get: function () {
  19626. return this._includeOnlyWithLayerMask;
  19627. },
  19628. /**
  19629. * Sets the layer id use to find what meshes are impacted by the light.
  19630. * Inactive if 0
  19631. */
  19632. set: function (value) {
  19633. this._includeOnlyWithLayerMask = value;
  19634. this._resyncMeshes();
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Light.prototype, "lightmapMode", {
  19640. /**
  19641. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19642. */
  19643. get: function () {
  19644. return this._lightmapMode;
  19645. },
  19646. /**
  19647. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19648. */
  19649. set: function (value) {
  19650. if (this._lightmapMode === value) {
  19651. return;
  19652. }
  19653. this._lightmapMode = value;
  19654. this._markMeshesAsLightDirty();
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. /**
  19660. * Returns the string "Light".
  19661. * @returns the class name
  19662. */
  19663. Light.prototype.getClassName = function () {
  19664. return "Light";
  19665. };
  19666. /**
  19667. * Converts the light information to a readable string for debug purpose.
  19668. * @param fullDetails Supports for multiple levels of logging within scene loading
  19669. * @returns the human readable light info
  19670. */
  19671. Light.prototype.toString = function (fullDetails) {
  19672. var ret = "Name: " + this.name;
  19673. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19674. if (this.animations) {
  19675. for (var i = 0; i < this.animations.length; i++) {
  19676. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19677. }
  19678. }
  19679. if (fullDetails) {
  19680. }
  19681. return ret;
  19682. };
  19683. /**
  19684. * Set the enabled state of this node.
  19685. * @param value - the new enabled state
  19686. */
  19687. Light.prototype.setEnabled = function (value) {
  19688. _super.prototype.setEnabled.call(this, value);
  19689. this._resyncMeshes();
  19690. };
  19691. /**
  19692. * Returns the Light associated shadow generator if any.
  19693. * @return the associated shadow generator.
  19694. */
  19695. Light.prototype.getShadowGenerator = function () {
  19696. return this._shadowGenerator;
  19697. };
  19698. /**
  19699. * Returns a Vector3, the absolute light position in the World.
  19700. * @returns the world space position of the light
  19701. */
  19702. Light.prototype.getAbsolutePosition = function () {
  19703. return BABYLON.Vector3.Zero();
  19704. };
  19705. /**
  19706. * Specifies if the light will affect the passed mesh.
  19707. * @param mesh The mesh to test against the light
  19708. * @return true the mesh is affected otherwise, false.
  19709. */
  19710. Light.prototype.canAffectMesh = function (mesh) {
  19711. if (!mesh) {
  19712. return true;
  19713. }
  19714. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19715. return false;
  19716. }
  19717. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19718. return false;
  19719. }
  19720. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19721. return false;
  19722. }
  19723. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19724. return false;
  19725. }
  19726. return true;
  19727. };
  19728. /**
  19729. * Computes and Returns the light World matrix.
  19730. * @returns the world matrix
  19731. */
  19732. Light.prototype.getWorldMatrix = function () {
  19733. this._currentRenderId = this.getScene().getRenderId();
  19734. var worldMatrix = this._getWorldMatrix();
  19735. if (this.parent && this.parent.getWorldMatrix) {
  19736. if (!this._parentedWorldMatrix) {
  19737. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19738. }
  19739. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19740. this._markSyncedWithParent();
  19741. return this._parentedWorldMatrix;
  19742. }
  19743. return worldMatrix;
  19744. };
  19745. /**
  19746. * Sort function to order lights for rendering.
  19747. * @param a First Light object to compare to second.
  19748. * @param b Second Light object to compare first.
  19749. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19750. */
  19751. Light.CompareLightsPriority = function (a, b) {
  19752. //shadow-casting lights have priority over non-shadow-casting lights
  19753. //the renderPrioirty is a secondary sort criterion
  19754. if (a.shadowEnabled !== b.shadowEnabled) {
  19755. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19756. }
  19757. return b.renderPriority - a.renderPriority;
  19758. };
  19759. /**
  19760. * Releases resources associated with this node.
  19761. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19762. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19763. */
  19764. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19765. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19766. if (this._shadowGenerator) {
  19767. this._shadowGenerator.dispose();
  19768. this._shadowGenerator = null;
  19769. }
  19770. // Animations
  19771. this.getScene().stopAnimation(this);
  19772. // Remove from meshes
  19773. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19774. var mesh = _a[_i];
  19775. mesh._removeLightSource(this);
  19776. }
  19777. this._uniformBuffer.dispose();
  19778. // Remove from scene
  19779. this.getScene().removeLight(this);
  19780. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19781. };
  19782. /**
  19783. * Returns the light type ID (integer).
  19784. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19785. */
  19786. Light.prototype.getTypeID = function () {
  19787. return 0;
  19788. };
  19789. /**
  19790. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19791. * @returns the scaled intensity in intensity mode unit
  19792. */
  19793. Light.prototype.getScaledIntensity = function () {
  19794. return this._photometricScale * this.intensity;
  19795. };
  19796. /**
  19797. * Returns a new Light object, named "name", from the current one.
  19798. * @param name The name of the cloned light
  19799. * @returns the new created light
  19800. */
  19801. Light.prototype.clone = function (name) {
  19802. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19803. if (!constructor) {
  19804. return null;
  19805. }
  19806. return BABYLON.SerializationHelper.Clone(constructor, this);
  19807. };
  19808. /**
  19809. * Serializes the current light into a Serialization object.
  19810. * @returns the serialized object.
  19811. */
  19812. Light.prototype.serialize = function () {
  19813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19814. // Type
  19815. serializationObject.type = this.getTypeID();
  19816. // Parent
  19817. if (this.parent) {
  19818. serializationObject.parentId = this.parent.id;
  19819. }
  19820. // Inclusion / exclusions
  19821. if (this.excludedMeshes.length > 0) {
  19822. serializationObject.excludedMeshesIds = [];
  19823. this.excludedMeshes.forEach(function (mesh) {
  19824. serializationObject.excludedMeshesIds.push(mesh.id);
  19825. });
  19826. }
  19827. if (this.includedOnlyMeshes.length > 0) {
  19828. serializationObject.includedOnlyMeshesIds = [];
  19829. this.includedOnlyMeshes.forEach(function (mesh) {
  19830. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19831. });
  19832. }
  19833. // Animations
  19834. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19835. serializationObject.ranges = this.serializeAnimationRanges();
  19836. return serializationObject;
  19837. };
  19838. /**
  19839. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19840. * This new light is named "name" and added to the passed scene.
  19841. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19842. * @param name The friendly name of the light
  19843. * @param scene The scene the new light will belong to
  19844. * @returns the constructor function
  19845. */
  19846. Light.GetConstructorFromName = function (type, name, scene) {
  19847. switch (type) {
  19848. case 0:
  19849. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19850. case 1:
  19851. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19852. case 2:
  19853. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19854. case 3:
  19855. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19856. }
  19857. return null;
  19858. };
  19859. /**
  19860. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19861. * @param parsedLight The JSON representation of the light
  19862. * @param scene The scene to create the parsed light in
  19863. * @returns the created light after parsing
  19864. */
  19865. Light.Parse = function (parsedLight, scene) {
  19866. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19867. if (!constructor) {
  19868. return null;
  19869. }
  19870. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19871. // Inclusion / exclusions
  19872. if (parsedLight.excludedMeshesIds) {
  19873. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19874. }
  19875. if (parsedLight.includedOnlyMeshesIds) {
  19876. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19877. }
  19878. // Parent
  19879. if (parsedLight.parentId) {
  19880. light._waitingParentId = parsedLight.parentId;
  19881. }
  19882. // Animations
  19883. if (parsedLight.animations) {
  19884. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19885. var parsedAnimation = parsedLight.animations[animationIndex];
  19886. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19887. }
  19888. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19889. }
  19890. if (parsedLight.autoAnimate) {
  19891. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19892. }
  19893. return light;
  19894. };
  19895. Light.prototype._hookArrayForExcluded = function (array) {
  19896. var _this = this;
  19897. var oldPush = array.push;
  19898. array.push = function () {
  19899. var items = [];
  19900. for (var _i = 0; _i < arguments.length; _i++) {
  19901. items[_i] = arguments[_i];
  19902. }
  19903. var result = oldPush.apply(array, items);
  19904. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19905. var item = items_1[_a];
  19906. item._resyncLighSource(_this);
  19907. }
  19908. return result;
  19909. };
  19910. var oldSplice = array.splice;
  19911. array.splice = function (index, deleteCount) {
  19912. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19913. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19914. var item = deleted_1[_i];
  19915. item._resyncLighSource(_this);
  19916. }
  19917. return deleted;
  19918. };
  19919. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19920. var item = array_1[_i];
  19921. item._resyncLighSource(this);
  19922. }
  19923. };
  19924. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19925. var _this = this;
  19926. var oldPush = array.push;
  19927. array.push = function () {
  19928. var items = [];
  19929. for (var _i = 0; _i < arguments.length; _i++) {
  19930. items[_i] = arguments[_i];
  19931. }
  19932. var result = oldPush.apply(array, items);
  19933. _this._resyncMeshes();
  19934. return result;
  19935. };
  19936. var oldSplice = array.splice;
  19937. array.splice = function (index, deleteCount) {
  19938. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19939. _this._resyncMeshes();
  19940. return deleted;
  19941. };
  19942. this._resyncMeshes();
  19943. };
  19944. Light.prototype._resyncMeshes = function () {
  19945. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19946. var mesh = _a[_i];
  19947. mesh._resyncLighSource(this);
  19948. }
  19949. };
  19950. /**
  19951. * Forces the meshes to update their light related information in their rendering used effects
  19952. * @ignore Internal Use Only
  19953. */
  19954. Light.prototype._markMeshesAsLightDirty = function () {
  19955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19956. var mesh = _a[_i];
  19957. if (mesh._lightSources.indexOf(this) !== -1) {
  19958. mesh._markSubMeshesAsLightDirty();
  19959. }
  19960. }
  19961. };
  19962. /**
  19963. * Recomputes the cached photometric scale if needed.
  19964. */
  19965. Light.prototype._computePhotometricScale = function () {
  19966. this._photometricScale = this._getPhotometricScale();
  19967. this.getScene().resetCachedMaterial();
  19968. };
  19969. /**
  19970. * Returns the Photometric Scale according to the light type and intensity mode.
  19971. */
  19972. Light.prototype._getPhotometricScale = function () {
  19973. var photometricScale = 0.0;
  19974. var lightTypeID = this.getTypeID();
  19975. //get photometric mode
  19976. var photometricMode = this.intensityMode;
  19977. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19978. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19979. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19980. }
  19981. else {
  19982. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19983. }
  19984. }
  19985. //compute photometric scale
  19986. switch (lightTypeID) {
  19987. case Light.LIGHTTYPEID_POINTLIGHT:
  19988. case Light.LIGHTTYPEID_SPOTLIGHT:
  19989. switch (photometricMode) {
  19990. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19991. photometricScale = 1.0 / (4.0 * Math.PI);
  19992. break;
  19993. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19994. photometricScale = 1.0;
  19995. break;
  19996. case Light.INTENSITYMODE_LUMINANCE:
  19997. photometricScale = this.radius * this.radius;
  19998. break;
  19999. }
  20000. break;
  20001. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  20002. switch (photometricMode) {
  20003. case Light.INTENSITYMODE_ILLUMINANCE:
  20004. photometricScale = 1.0;
  20005. break;
  20006. case Light.INTENSITYMODE_LUMINANCE:
  20007. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  20008. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  20009. var apexAngleRadians = this.radius;
  20010. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  20011. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  20012. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  20013. photometricScale = solidAngle;
  20014. break;
  20015. }
  20016. break;
  20017. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  20018. // No fall off in hemisperic light.
  20019. photometricScale = 1.0;
  20020. break;
  20021. }
  20022. return photometricScale;
  20023. };
  20024. /**
  20025. * Reorder the light in the scene according to their defined priority.
  20026. * @ignore Internal Use Only
  20027. */
  20028. Light.prototype._reorderLightsInScene = function () {
  20029. var scene = this.getScene();
  20030. if (this._renderPriority != 0) {
  20031. scene.requireLightSorting = true;
  20032. }
  20033. this.getScene().sortLightsByPriority();
  20034. };
  20035. //lightmapMode Consts
  20036. Light._LIGHTMAP_DEFAULT = 0;
  20037. Light._LIGHTMAP_SPECULAR = 1;
  20038. Light._LIGHTMAP_SHADOWSONLY = 2;
  20039. // Intensity Mode Consts
  20040. Light._INTENSITYMODE_AUTOMATIC = 0;
  20041. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  20042. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  20043. Light._INTENSITYMODE_ILLUMINANCE = 3;
  20044. Light._INTENSITYMODE_LUMINANCE = 4;
  20045. // Light types ids const.
  20046. Light._LIGHTTYPEID_POINTLIGHT = 0;
  20047. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  20048. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  20049. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  20050. __decorate([
  20051. BABYLON.serializeAsColor3()
  20052. ], Light.prototype, "diffuse", void 0);
  20053. __decorate([
  20054. BABYLON.serializeAsColor3()
  20055. ], Light.prototype, "specular", void 0);
  20056. __decorate([
  20057. BABYLON.serialize()
  20058. ], Light.prototype, "intensity", void 0);
  20059. __decorate([
  20060. BABYLON.serialize()
  20061. ], Light.prototype, "range", void 0);
  20062. __decorate([
  20063. BABYLON.serialize()
  20064. ], Light.prototype, "intensityMode", null);
  20065. __decorate([
  20066. BABYLON.serialize()
  20067. ], Light.prototype, "radius", null);
  20068. __decorate([
  20069. BABYLON.serialize()
  20070. ], Light.prototype, "_renderPriority", void 0);
  20071. __decorate([
  20072. BABYLON.expandToProperty("_reorderLightsInScene")
  20073. ], Light.prototype, "renderPriority", void 0);
  20074. __decorate([
  20075. BABYLON.serialize()
  20076. ], Light.prototype, "shadowEnabled", void 0);
  20077. __decorate([
  20078. BABYLON.serialize("excludeWithLayerMask")
  20079. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20080. __decorate([
  20081. BABYLON.serialize("includeOnlyWithLayerMask")
  20082. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20083. __decorate([
  20084. BABYLON.serialize("lightmapMode")
  20085. ], Light.prototype, "_lightmapMode", void 0);
  20086. return Light;
  20087. }(BABYLON.Node));
  20088. BABYLON.Light = Light;
  20089. })(BABYLON || (BABYLON = {}));
  20090. //# sourceMappingURL=babylon.light.js.map
  20091. "use strict";
  20092. var BABYLON;
  20093. (function (BABYLON) {
  20094. var Camera = /** @class */ (function (_super) {
  20095. __extends(Camera, _super);
  20096. function Camera(name, position, scene) {
  20097. var _this = _super.call(this, name, scene) || this;
  20098. /**
  20099. * The vector the camera should consider as up.
  20100. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20101. */
  20102. _this.upVector = BABYLON.Vector3.Up();
  20103. _this.orthoLeft = null;
  20104. _this.orthoRight = null;
  20105. _this.orthoBottom = null;
  20106. _this.orthoTop = null;
  20107. /**
  20108. * FOV is set in Radians. (default is 0.8)
  20109. */
  20110. _this.fov = 0.8;
  20111. _this.minZ = 1;
  20112. _this.maxZ = 10000.0;
  20113. _this.inertia = 0.9;
  20114. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20115. _this.isIntermediate = false;
  20116. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20117. /**
  20118. * Restricts the camera to viewing objects with the same layerMask.
  20119. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20120. */
  20121. _this.layerMask = 0x0FFFFFFF;
  20122. /**
  20123. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20124. */
  20125. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20126. // Camera rig members
  20127. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20128. _this._rigCameras = new Array();
  20129. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20130. _this._skipRendering = false;
  20131. _this.customRenderTargets = new Array();
  20132. // Observables
  20133. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20134. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20135. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20136. _this.onRestoreStateObservable = new BABYLON.Observable();
  20137. // Cache
  20138. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20139. _this._projectionMatrix = new BABYLON.Matrix();
  20140. _this._doNotComputeProjectionMatrix = false;
  20141. _this._postProcesses = new Array();
  20142. _this._transformMatrix = BABYLON.Matrix.Zero();
  20143. _this._activeMeshes = new BABYLON.SmartArray(256);
  20144. _this._globalPosition = BABYLON.Vector3.Zero();
  20145. _this._refreshFrustumPlanes = true;
  20146. _this.getScene().addCamera(_this);
  20147. if (!_this.getScene().activeCamera) {
  20148. _this.getScene().activeCamera = _this;
  20149. }
  20150. _this.position = position;
  20151. return _this;
  20152. }
  20153. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20154. get: function () {
  20155. return Camera._PERSPECTIVE_CAMERA;
  20156. },
  20157. enumerable: true,
  20158. configurable: true
  20159. });
  20160. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20161. get: function () {
  20162. return Camera._ORTHOGRAPHIC_CAMERA;
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20168. /**
  20169. * This is the default FOV mode for perspective cameras.
  20170. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20171. *
  20172. */
  20173. get: function () {
  20174. return Camera._FOVMODE_VERTICAL_FIXED;
  20175. },
  20176. enumerable: true,
  20177. configurable: true
  20178. });
  20179. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20180. /**
  20181. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20182. *
  20183. */
  20184. get: function () {
  20185. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20191. get: function () {
  20192. return Camera._RIG_MODE_NONE;
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20198. get: function () {
  20199. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20205. get: function () {
  20206. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20207. },
  20208. enumerable: true,
  20209. configurable: true
  20210. });
  20211. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20212. get: function () {
  20213. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20214. },
  20215. enumerable: true,
  20216. configurable: true
  20217. });
  20218. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20219. get: function () {
  20220. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20221. },
  20222. enumerable: true,
  20223. configurable: true
  20224. });
  20225. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20226. get: function () {
  20227. return Camera._RIG_MODE_VR;
  20228. },
  20229. enumerable: true,
  20230. configurable: true
  20231. });
  20232. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20233. get: function () {
  20234. return Camera._RIG_MODE_WEBVR;
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. /**
  20240. * Store current camera state (fov, position, etc..)
  20241. */
  20242. Camera.prototype.storeState = function () {
  20243. this._stateStored = true;
  20244. this._storedFov = this.fov;
  20245. return this;
  20246. };
  20247. /**
  20248. * Restores the camera state values if it has been stored. You must call storeState() first
  20249. */
  20250. Camera.prototype._restoreStateValues = function () {
  20251. if (!this._stateStored) {
  20252. return false;
  20253. }
  20254. this.fov = this._storedFov;
  20255. return true;
  20256. };
  20257. /**
  20258. * Restored camera state. You must call storeState() first
  20259. */
  20260. Camera.prototype.restoreState = function () {
  20261. if (this._restoreStateValues()) {
  20262. this.onRestoreStateObservable.notifyObservers(this);
  20263. return true;
  20264. }
  20265. return false;
  20266. };
  20267. Camera.prototype.getClassName = function () {
  20268. return "Camera";
  20269. };
  20270. /**
  20271. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20272. */
  20273. Camera.prototype.toString = function (fullDetails) {
  20274. var ret = "Name: " + this.name;
  20275. ret += ", type: " + this.getClassName();
  20276. if (this.animations) {
  20277. for (var i = 0; i < this.animations.length; i++) {
  20278. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20279. }
  20280. }
  20281. if (fullDetails) {
  20282. }
  20283. return ret;
  20284. };
  20285. Object.defineProperty(Camera.prototype, "globalPosition", {
  20286. get: function () {
  20287. return this._globalPosition;
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Camera.prototype.getActiveMeshes = function () {
  20293. return this._activeMeshes;
  20294. };
  20295. Camera.prototype.isActiveMesh = function (mesh) {
  20296. return (this._activeMeshes.indexOf(mesh) !== -1);
  20297. };
  20298. /**
  20299. * Is this camera ready to be used/rendered
  20300. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20301. * @return true if the camera is ready
  20302. */
  20303. Camera.prototype.isReady = function (completeCheck) {
  20304. if (completeCheck === void 0) { completeCheck = false; }
  20305. if (completeCheck) {
  20306. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20307. var pp = _a[_i];
  20308. if (pp && !pp.isReady()) {
  20309. return false;
  20310. }
  20311. }
  20312. }
  20313. return _super.prototype.isReady.call(this, completeCheck);
  20314. };
  20315. //Cache
  20316. Camera.prototype._initCache = function () {
  20317. _super.prototype._initCache.call(this);
  20318. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20319. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20320. this._cache.mode = undefined;
  20321. this._cache.minZ = undefined;
  20322. this._cache.maxZ = undefined;
  20323. this._cache.fov = undefined;
  20324. this._cache.fovMode = undefined;
  20325. this._cache.aspectRatio = undefined;
  20326. this._cache.orthoLeft = undefined;
  20327. this._cache.orthoRight = undefined;
  20328. this._cache.orthoBottom = undefined;
  20329. this._cache.orthoTop = undefined;
  20330. this._cache.renderWidth = undefined;
  20331. this._cache.renderHeight = undefined;
  20332. };
  20333. Camera.prototype._updateCache = function (ignoreParentClass) {
  20334. if (!ignoreParentClass) {
  20335. _super.prototype._updateCache.call(this);
  20336. }
  20337. this._cache.position.copyFrom(this.position);
  20338. this._cache.upVector.copyFrom(this.upVector);
  20339. };
  20340. // Synchronized
  20341. Camera.prototype._isSynchronized = function () {
  20342. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20343. };
  20344. Camera.prototype._isSynchronizedViewMatrix = function () {
  20345. if (!_super.prototype._isSynchronized.call(this))
  20346. return false;
  20347. return this._cache.position.equals(this.position)
  20348. && this._cache.upVector.equals(this.upVector)
  20349. && this.isSynchronizedWithParent();
  20350. };
  20351. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20352. var check = this._cache.mode === this.mode
  20353. && this._cache.minZ === this.minZ
  20354. && this._cache.maxZ === this.maxZ;
  20355. if (!check) {
  20356. return false;
  20357. }
  20358. var engine = this.getEngine();
  20359. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20360. check = this._cache.fov === this.fov
  20361. && this._cache.fovMode === this.fovMode
  20362. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20363. }
  20364. else {
  20365. check = this._cache.orthoLeft === this.orthoLeft
  20366. && this._cache.orthoRight === this.orthoRight
  20367. && this._cache.orthoBottom === this.orthoBottom
  20368. && this._cache.orthoTop === this.orthoTop
  20369. && this._cache.renderWidth === engine.getRenderWidth()
  20370. && this._cache.renderHeight === engine.getRenderHeight();
  20371. }
  20372. return check;
  20373. };
  20374. // Controls
  20375. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20376. };
  20377. Camera.prototype.detachControl = function (element) {
  20378. };
  20379. Camera.prototype.update = function () {
  20380. this._checkInputs();
  20381. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20382. this._updateRigCameras();
  20383. }
  20384. };
  20385. Camera.prototype._checkInputs = function () {
  20386. this.onAfterCheckInputsObservable.notifyObservers(this);
  20387. };
  20388. Object.defineProperty(Camera.prototype, "rigCameras", {
  20389. get: function () {
  20390. return this._rigCameras;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20396. get: function () {
  20397. return this._rigPostProcess;
  20398. },
  20399. enumerable: true,
  20400. configurable: true
  20401. });
  20402. /**
  20403. * Internal, gets the first post proces.
  20404. * @returns the first post process to be run on this camera.
  20405. */
  20406. Camera.prototype._getFirstPostProcess = function () {
  20407. for (var pp in this._postProcesses) {
  20408. if (this._postProcesses[pp] !== null) {
  20409. return this._postProcesses[pp];
  20410. }
  20411. }
  20412. return null;
  20413. };
  20414. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20415. // invalidate framebuffer
  20416. var firstPostProcess = this._getFirstPostProcess();
  20417. if (firstPostProcess) {
  20418. firstPostProcess.markTextureDirty();
  20419. }
  20420. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20421. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20422. var cam = this._rigCameras[i];
  20423. var rigPostProcess = cam._rigPostProcess;
  20424. // for VR rig, there does not have to be a post process
  20425. if (rigPostProcess) {
  20426. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20427. if (isPass) {
  20428. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20429. cam.isIntermediate = this._postProcesses.length === 0;
  20430. }
  20431. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20432. rigPostProcess.markTextureDirty();
  20433. }
  20434. else {
  20435. cam._postProcesses = this._postProcesses.slice(0);
  20436. }
  20437. }
  20438. };
  20439. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20440. if (insertAt === void 0) { insertAt = null; }
  20441. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20442. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20443. return 0;
  20444. }
  20445. if (insertAt == null || insertAt < 0) {
  20446. this._postProcesses.push(postProcess);
  20447. }
  20448. else if (this._postProcesses[insertAt] === null) {
  20449. this._postProcesses[insertAt] = postProcess;
  20450. }
  20451. else {
  20452. this._postProcesses.splice(insertAt, 0, postProcess);
  20453. }
  20454. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20455. return this._postProcesses.indexOf(postProcess);
  20456. };
  20457. Camera.prototype.detachPostProcess = function (postProcess) {
  20458. var idx = this._postProcesses.indexOf(postProcess);
  20459. if (idx !== -1) {
  20460. this._postProcesses[idx] = null;
  20461. }
  20462. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20463. };
  20464. Camera.prototype.getWorldMatrix = function () {
  20465. if (!this._worldMatrix) {
  20466. this._worldMatrix = BABYLON.Matrix.Identity();
  20467. }
  20468. var viewMatrix = this.getViewMatrix();
  20469. viewMatrix.invertToRef(this._worldMatrix);
  20470. return this._worldMatrix;
  20471. };
  20472. Camera.prototype._getViewMatrix = function () {
  20473. return BABYLON.Matrix.Identity();
  20474. };
  20475. Camera.prototype.getViewMatrix = function (force) {
  20476. if (!force && this._isSynchronizedViewMatrix()) {
  20477. return this._computedViewMatrix;
  20478. }
  20479. this.updateCache();
  20480. this._computedViewMatrix = this._getViewMatrix();
  20481. this._currentRenderId = this.getScene().getRenderId();
  20482. this._refreshFrustumPlanes = true;
  20483. if (!this.parent || !this.parent.getWorldMatrix) {
  20484. this._globalPosition.copyFrom(this.position);
  20485. }
  20486. else {
  20487. if (!this._worldMatrix) {
  20488. this._worldMatrix = BABYLON.Matrix.Identity();
  20489. }
  20490. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20491. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20492. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20493. this._computedViewMatrix.invert();
  20494. this._markSyncedWithParent();
  20495. }
  20496. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20497. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20498. }
  20499. this.onViewMatrixChangedObservable.notifyObservers(this);
  20500. return this._computedViewMatrix;
  20501. };
  20502. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20503. this._doNotComputeProjectionMatrix = true;
  20504. if (projection !== undefined) {
  20505. this._projectionMatrix = projection;
  20506. }
  20507. };
  20508. ;
  20509. Camera.prototype.unfreezeProjectionMatrix = function () {
  20510. this._doNotComputeProjectionMatrix = false;
  20511. };
  20512. ;
  20513. Camera.prototype.getProjectionMatrix = function (force) {
  20514. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20515. return this._projectionMatrix;
  20516. }
  20517. // Cache
  20518. this._cache.mode = this.mode;
  20519. this._cache.minZ = this.minZ;
  20520. this._cache.maxZ = this.maxZ;
  20521. // Matrix
  20522. this._refreshFrustumPlanes = true;
  20523. var engine = this.getEngine();
  20524. var scene = this.getScene();
  20525. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20526. this._cache.fov = this.fov;
  20527. this._cache.fovMode = this.fovMode;
  20528. this._cache.aspectRatio = engine.getAspectRatio(this);
  20529. if (this.minZ <= 0) {
  20530. this.minZ = 0.1;
  20531. }
  20532. if (scene.useRightHandedSystem) {
  20533. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20534. }
  20535. else {
  20536. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20537. }
  20538. }
  20539. else {
  20540. var halfWidth = engine.getRenderWidth() / 2.0;
  20541. var halfHeight = engine.getRenderHeight() / 2.0;
  20542. if (scene.useRightHandedSystem) {
  20543. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20544. }
  20545. else {
  20546. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20547. }
  20548. this._cache.orthoLeft = this.orthoLeft;
  20549. this._cache.orthoRight = this.orthoRight;
  20550. this._cache.orthoBottom = this.orthoBottom;
  20551. this._cache.orthoTop = this.orthoTop;
  20552. this._cache.renderWidth = engine.getRenderWidth();
  20553. this._cache.renderHeight = engine.getRenderHeight();
  20554. }
  20555. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20556. return this._projectionMatrix;
  20557. };
  20558. Camera.prototype.getTranformationMatrix = function () {
  20559. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20560. return this._transformMatrix;
  20561. };
  20562. Camera.prototype.updateFrustumPlanes = function () {
  20563. if (!this._refreshFrustumPlanes) {
  20564. return;
  20565. }
  20566. this.getTranformationMatrix();
  20567. if (!this._frustumPlanes) {
  20568. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20569. }
  20570. else {
  20571. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20572. }
  20573. this._refreshFrustumPlanes = false;
  20574. };
  20575. Camera.prototype.isInFrustum = function (target) {
  20576. this.updateFrustumPlanes();
  20577. return target.isInFrustum(this._frustumPlanes);
  20578. };
  20579. Camera.prototype.isCompletelyInFrustum = function (target) {
  20580. this.updateFrustumPlanes();
  20581. return target.isCompletelyInFrustum(this._frustumPlanes);
  20582. };
  20583. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20584. if (length === void 0) { length = 100; }
  20585. if (!transform) {
  20586. transform = this.getWorldMatrix();
  20587. }
  20588. if (!origin) {
  20589. origin = this.position;
  20590. }
  20591. var forward = new BABYLON.Vector3(0, 0, 1);
  20592. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20593. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20594. return new BABYLON.Ray(origin, direction, length);
  20595. };
  20596. /**
  20597. * Releases resources associated with this node.
  20598. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20599. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20600. */
  20601. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20602. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20603. // Observables
  20604. this.onViewMatrixChangedObservable.clear();
  20605. this.onProjectionMatrixChangedObservable.clear();
  20606. this.onAfterCheckInputsObservable.clear();
  20607. this.onRestoreStateObservable.clear();
  20608. // Inputs
  20609. if (this.inputs) {
  20610. this.inputs.clear();
  20611. }
  20612. // Animations
  20613. this.getScene().stopAnimation(this);
  20614. // Remove from scene
  20615. this.getScene().removeCamera(this);
  20616. while (this._rigCameras.length > 0) {
  20617. var camera = this._rigCameras.pop();
  20618. if (camera) {
  20619. camera.dispose();
  20620. }
  20621. }
  20622. // Postprocesses
  20623. if (this._rigPostProcess) {
  20624. this._rigPostProcess.dispose(this);
  20625. this._rigPostProcess = null;
  20626. this._postProcesses = [];
  20627. }
  20628. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20629. this._rigPostProcess = null;
  20630. this._postProcesses = [];
  20631. }
  20632. else {
  20633. var i = this._postProcesses.length;
  20634. while (--i >= 0) {
  20635. var postProcess = this._postProcesses[i];
  20636. if (postProcess) {
  20637. postProcess.dispose(this);
  20638. }
  20639. }
  20640. }
  20641. // Render targets
  20642. var i = this.customRenderTargets.length;
  20643. while (--i >= 0) {
  20644. this.customRenderTargets[i].dispose();
  20645. }
  20646. this.customRenderTargets = [];
  20647. // Active Meshes
  20648. this._activeMeshes.dispose();
  20649. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20650. };
  20651. Object.defineProperty(Camera.prototype, "leftCamera", {
  20652. // ---- Camera rigs section ----
  20653. get: function () {
  20654. if (this._rigCameras.length < 1) {
  20655. return null;
  20656. }
  20657. return this._rigCameras[0];
  20658. },
  20659. enumerable: true,
  20660. configurable: true
  20661. });
  20662. Object.defineProperty(Camera.prototype, "rightCamera", {
  20663. get: function () {
  20664. if (this._rigCameras.length < 2) {
  20665. return null;
  20666. }
  20667. return this._rigCameras[1];
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. Camera.prototype.getLeftTarget = function () {
  20673. if (this._rigCameras.length < 1) {
  20674. return null;
  20675. }
  20676. return this._rigCameras[0].getTarget();
  20677. };
  20678. Camera.prototype.getRightTarget = function () {
  20679. if (this._rigCameras.length < 2) {
  20680. return null;
  20681. }
  20682. return this._rigCameras[1].getTarget();
  20683. };
  20684. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20685. if (this.cameraRigMode === mode) {
  20686. return;
  20687. }
  20688. while (this._rigCameras.length > 0) {
  20689. var camera = this._rigCameras.pop();
  20690. if (camera) {
  20691. camera.dispose();
  20692. }
  20693. }
  20694. this.cameraRigMode = mode;
  20695. this._cameraRigParams = {};
  20696. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20697. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20698. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20699. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20700. // create the rig cameras, unless none
  20701. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20702. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20703. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20704. if (leftCamera && rightCamera) {
  20705. this._rigCameras.push(leftCamera);
  20706. this._rigCameras.push(rightCamera);
  20707. }
  20708. }
  20709. switch (this.cameraRigMode) {
  20710. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20711. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20712. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20713. break;
  20714. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20715. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20716. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20717. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20718. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20719. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20720. break;
  20721. case Camera.RIG_MODE_VR:
  20722. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20723. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20724. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20725. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20726. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20727. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20728. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20729. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20730. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20731. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20732. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20733. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20734. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20735. if (metrics.compensateDistortion) {
  20736. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20737. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20738. }
  20739. break;
  20740. case Camera.RIG_MODE_WEBVR:
  20741. if (rigParams.vrDisplay) {
  20742. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20743. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20744. //Left eye
  20745. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20746. this._rigCameras[0].setCameraRigParameter("left", true);
  20747. //leaving this for future reference
  20748. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20749. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20750. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20751. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20752. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20753. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20754. this._rigCameras[0].parent = this;
  20755. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20756. //Right eye
  20757. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20758. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20759. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20760. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20761. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20762. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20763. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20764. this._rigCameras[1].parent = this;
  20765. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20766. if (Camera.UseAlternateWebVRRendering) {
  20767. this._rigCameras[1]._skipRendering = true;
  20768. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20769. }
  20770. }
  20771. break;
  20772. }
  20773. this._cascadePostProcessesToRigCams();
  20774. this.update();
  20775. };
  20776. Camera.prototype._getVRProjectionMatrix = function () {
  20777. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20778. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20779. return this._projectionMatrix;
  20780. };
  20781. Camera.prototype._updateCameraRotationMatrix = function () {
  20782. //Here for WebVR
  20783. };
  20784. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20785. //Here for WebVR
  20786. };
  20787. /**
  20788. * This function MUST be overwritten by the different WebVR cameras available.
  20789. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20790. */
  20791. Camera.prototype._getWebVRProjectionMatrix = function () {
  20792. return BABYLON.Matrix.Identity();
  20793. };
  20794. /**
  20795. * This function MUST be overwritten by the different WebVR cameras available.
  20796. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20797. */
  20798. Camera.prototype._getWebVRViewMatrix = function () {
  20799. return BABYLON.Matrix.Identity();
  20800. };
  20801. Camera.prototype.setCameraRigParameter = function (name, value) {
  20802. if (!this._cameraRigParams) {
  20803. this._cameraRigParams = {};
  20804. }
  20805. this._cameraRigParams[name] = value;
  20806. //provisionnally:
  20807. if (name === "interaxialDistance") {
  20808. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20809. }
  20810. };
  20811. /**
  20812. * needs to be overridden by children so sub has required properties to be copied
  20813. */
  20814. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20815. return null;
  20816. };
  20817. /**
  20818. * May need to be overridden by children
  20819. */
  20820. Camera.prototype._updateRigCameras = function () {
  20821. for (var i = 0; i < this._rigCameras.length; i++) {
  20822. this._rigCameras[i].minZ = this.minZ;
  20823. this._rigCameras[i].maxZ = this.maxZ;
  20824. this._rigCameras[i].fov = this.fov;
  20825. }
  20826. // only update viewport when ANAGLYPH
  20827. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20828. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20829. }
  20830. };
  20831. Camera.prototype._setupInputs = function () {
  20832. };
  20833. Camera.prototype.serialize = function () {
  20834. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20835. // Type
  20836. serializationObject.type = this.getClassName();
  20837. // Parent
  20838. if (this.parent) {
  20839. serializationObject.parentId = this.parent.id;
  20840. }
  20841. if (this.inputs) {
  20842. this.inputs.serialize(serializationObject);
  20843. }
  20844. // Animations
  20845. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20846. serializationObject.ranges = this.serializeAnimationRanges();
  20847. return serializationObject;
  20848. };
  20849. Camera.prototype.clone = function (name) {
  20850. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20851. };
  20852. Camera.prototype.getDirection = function (localAxis) {
  20853. var result = BABYLON.Vector3.Zero();
  20854. this.getDirectionToRef(localAxis, result);
  20855. return result;
  20856. };
  20857. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20858. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20859. };
  20860. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20861. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20862. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20863. switch (type) {
  20864. case "ArcRotateCamera":
  20865. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20866. case "DeviceOrientationCamera":
  20867. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20868. case "FollowCamera":
  20869. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20870. case "ArcFollowCamera":
  20871. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20872. case "GamepadCamera":
  20873. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20874. case "TouchCamera":
  20875. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20876. case "VirtualJoysticksCamera":
  20877. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20878. case "WebVRFreeCamera":
  20879. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20880. case "WebVRGamepadCamera":
  20881. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20882. case "VRDeviceOrientationFreeCamera":
  20883. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20884. case "VRDeviceOrientationGamepadCamera":
  20885. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20886. case "AnaglyphArcRotateCamera":
  20887. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20888. case "AnaglyphFreeCamera":
  20889. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20890. case "AnaglyphGamepadCamera":
  20891. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20892. case "AnaglyphUniversalCamera":
  20893. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20894. case "StereoscopicArcRotateCamera":
  20895. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20896. case "StereoscopicFreeCamera":
  20897. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20898. case "StereoscopicGamepadCamera":
  20899. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20900. case "StereoscopicUniversalCamera":
  20901. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20902. case "FreeCamera":// Forcing Universal here
  20903. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20904. default:// Universal Camera is the default value
  20905. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20906. }
  20907. };
  20908. Camera.prototype.computeWorldMatrix = function () {
  20909. return this.getWorldMatrix();
  20910. };
  20911. Camera.Parse = function (parsedCamera, scene) {
  20912. var type = parsedCamera.type;
  20913. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20914. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20915. // Parent
  20916. if (parsedCamera.parentId) {
  20917. camera._waitingParentId = parsedCamera.parentId;
  20918. }
  20919. //If camera has an input manager, let it parse inputs settings
  20920. if (camera.inputs) {
  20921. camera.inputs.parse(parsedCamera);
  20922. camera._setupInputs();
  20923. }
  20924. if (camera.setPosition) {
  20925. camera.position.copyFromFloats(0, 0, 0);
  20926. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20927. }
  20928. // Target
  20929. if (parsedCamera.target) {
  20930. if (camera.setTarget) {
  20931. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20932. }
  20933. }
  20934. // Apply 3d rig, when found
  20935. if (parsedCamera.cameraRigMode) {
  20936. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20937. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20938. }
  20939. // Animations
  20940. if (parsedCamera.animations) {
  20941. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20942. var parsedAnimation = parsedCamera.animations[animationIndex];
  20943. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20944. }
  20945. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20946. }
  20947. if (parsedCamera.autoAnimate) {
  20948. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20949. }
  20950. return camera;
  20951. };
  20952. // Statics
  20953. Camera._PERSPECTIVE_CAMERA = 0;
  20954. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20955. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20956. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20957. Camera._RIG_MODE_NONE = 0;
  20958. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20959. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20960. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20961. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20962. Camera._RIG_MODE_VR = 20;
  20963. Camera._RIG_MODE_WEBVR = 21;
  20964. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20965. Camera.UseAlternateWebVRRendering = false;
  20966. __decorate([
  20967. BABYLON.serializeAsVector3()
  20968. ], Camera.prototype, "position", void 0);
  20969. __decorate([
  20970. BABYLON.serializeAsVector3()
  20971. ], Camera.prototype, "upVector", void 0);
  20972. __decorate([
  20973. BABYLON.serialize()
  20974. ], Camera.prototype, "orthoLeft", void 0);
  20975. __decorate([
  20976. BABYLON.serialize()
  20977. ], Camera.prototype, "orthoRight", void 0);
  20978. __decorate([
  20979. BABYLON.serialize()
  20980. ], Camera.prototype, "orthoBottom", void 0);
  20981. __decorate([
  20982. BABYLON.serialize()
  20983. ], Camera.prototype, "orthoTop", void 0);
  20984. __decorate([
  20985. BABYLON.serialize()
  20986. ], Camera.prototype, "fov", void 0);
  20987. __decorate([
  20988. BABYLON.serialize()
  20989. ], Camera.prototype, "minZ", void 0);
  20990. __decorate([
  20991. BABYLON.serialize()
  20992. ], Camera.prototype, "maxZ", void 0);
  20993. __decorate([
  20994. BABYLON.serialize()
  20995. ], Camera.prototype, "inertia", void 0);
  20996. __decorate([
  20997. BABYLON.serialize()
  20998. ], Camera.prototype, "mode", void 0);
  20999. __decorate([
  21000. BABYLON.serialize()
  21001. ], Camera.prototype, "layerMask", void 0);
  21002. __decorate([
  21003. BABYLON.serialize()
  21004. ], Camera.prototype, "fovMode", void 0);
  21005. __decorate([
  21006. BABYLON.serialize()
  21007. ], Camera.prototype, "cameraRigMode", void 0);
  21008. __decorate([
  21009. BABYLON.serialize()
  21010. ], Camera.prototype, "interaxialDistance", void 0);
  21011. __decorate([
  21012. BABYLON.serialize()
  21013. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  21014. return Camera;
  21015. }(BABYLON.Node));
  21016. BABYLON.Camera = Camera;
  21017. })(BABYLON || (BABYLON = {}));
  21018. //# sourceMappingURL=babylon.camera.js.map
  21019. "use strict";
  21020. var BABYLON;
  21021. (function (BABYLON) {
  21022. var RenderingManager = /** @class */ (function () {
  21023. function RenderingManager(scene) {
  21024. this._renderingGroups = new Array();
  21025. this._autoClearDepthStencil = {};
  21026. this._customOpaqueSortCompareFn = {};
  21027. this._customAlphaTestSortCompareFn = {};
  21028. this._customTransparentSortCompareFn = {};
  21029. this._renderinGroupInfo = null;
  21030. this._scene = scene;
  21031. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  21032. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  21033. }
  21034. }
  21035. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  21036. if (depth === void 0) { depth = true; }
  21037. if (stencil === void 0) { stencil = true; }
  21038. if (this._depthStencilBufferAlreadyCleaned) {
  21039. return;
  21040. }
  21041. this._scene.getEngine().clear(null, false, depth, stencil);
  21042. this._depthStencilBufferAlreadyCleaned = true;
  21043. };
  21044. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  21045. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  21046. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  21047. var info = null;
  21048. if (observable) {
  21049. if (!this._renderinGroupInfo) {
  21050. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  21051. }
  21052. info = this._renderinGroupInfo;
  21053. info.scene = this._scene;
  21054. info.camera = this._scene.activeCamera;
  21055. }
  21056. // Dispatch sprites
  21057. if (renderSprites) {
  21058. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  21059. var manager = this._scene.spriteManagers[index];
  21060. this.dispatchSprites(manager);
  21061. }
  21062. }
  21063. // Render
  21064. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21065. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  21066. var renderingGroup = this._renderingGroups[index];
  21067. if (!renderingGroup && !observable)
  21068. continue;
  21069. var renderingGroupMask = 0;
  21070. // Fire PRECLEAR stage
  21071. if (observable && info) {
  21072. renderingGroupMask = Math.pow(2, index);
  21073. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21074. info.renderingGroupId = index;
  21075. observable.notifyObservers(info, renderingGroupMask);
  21076. }
  21077. // Clear depth/stencil if needed
  21078. if (RenderingManager.AUTOCLEAR) {
  21079. var autoClear = this._autoClearDepthStencil[index];
  21080. if (autoClear && autoClear.autoClear) {
  21081. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21082. }
  21083. }
  21084. if (observable && info) {
  21085. // Fire PREOPAQUE stage
  21086. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21087. observable.notifyObservers(info, renderingGroupMask);
  21088. // Fire PRETRANSPARENT stage
  21089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21090. observable.notifyObservers(info, renderingGroupMask);
  21091. }
  21092. if (renderingGroup)
  21093. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21094. // Fire POSTTRANSPARENT stage
  21095. if (observable && info) {
  21096. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21097. observable.notifyObservers(info, renderingGroupMask);
  21098. }
  21099. }
  21100. };
  21101. RenderingManager.prototype.reset = function () {
  21102. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21103. var renderingGroup = this._renderingGroups[index];
  21104. if (renderingGroup) {
  21105. renderingGroup.prepare();
  21106. }
  21107. }
  21108. };
  21109. RenderingManager.prototype.dispose = function () {
  21110. this.freeRenderingGroups();
  21111. this._renderingGroups.length = 0;
  21112. };
  21113. /**
  21114. * Clear the info related to rendering groups preventing retention points during dispose.
  21115. */
  21116. RenderingManager.prototype.freeRenderingGroups = function () {
  21117. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21118. var renderingGroup = this._renderingGroups[index];
  21119. if (renderingGroup) {
  21120. renderingGroup.dispose();
  21121. }
  21122. }
  21123. };
  21124. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21125. if (this._renderingGroups[renderingGroupId] === undefined) {
  21126. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21127. }
  21128. };
  21129. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21130. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21131. this._prepareRenderingGroup(renderingGroupId);
  21132. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21133. };
  21134. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21135. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21136. this._prepareRenderingGroup(renderingGroupId);
  21137. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21138. };
  21139. /**
  21140. * @param subMesh The submesh to dispatch
  21141. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21142. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21143. */
  21144. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21145. if (mesh === undefined) {
  21146. mesh = subMesh.getMesh();
  21147. }
  21148. var renderingGroupId = mesh.renderingGroupId || 0;
  21149. this._prepareRenderingGroup(renderingGroupId);
  21150. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21151. };
  21152. /**
  21153. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21154. * This allowed control for front to back rendering or reversly depending of the special needs.
  21155. *
  21156. * @param renderingGroupId The rendering group id corresponding to its index
  21157. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21158. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21159. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21160. */
  21161. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21162. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21163. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21164. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21165. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21166. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21167. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21168. if (this._renderingGroups[renderingGroupId]) {
  21169. var group = this._renderingGroups[renderingGroupId];
  21170. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21171. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21172. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21173. }
  21174. };
  21175. /**
  21176. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21177. *
  21178. * @param renderingGroupId The rendering group id corresponding to its index
  21179. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21180. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21181. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21182. */
  21183. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21184. if (depth === void 0) { depth = true; }
  21185. if (stencil === void 0) { stencil = true; }
  21186. this._autoClearDepthStencil[renderingGroupId] = {
  21187. autoClear: autoClearDepthStencil,
  21188. depth: depth,
  21189. stencil: stencil
  21190. };
  21191. };
  21192. /**
  21193. * The max id used for rendering groups (not included)
  21194. */
  21195. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21196. /**
  21197. * The min id used for rendering groups (included)
  21198. */
  21199. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21200. /**
  21201. * Used to globally prevent autoclearing scenes.
  21202. */
  21203. RenderingManager.AUTOCLEAR = true;
  21204. return RenderingManager;
  21205. }());
  21206. BABYLON.RenderingManager = RenderingManager;
  21207. })(BABYLON || (BABYLON = {}));
  21208. //# sourceMappingURL=babylon.renderingManager.js.map
  21209. "use strict";
  21210. var BABYLON;
  21211. (function (BABYLON) {
  21212. var RenderingGroup = /** @class */ (function () {
  21213. /**
  21214. * Creates a new rendering group.
  21215. * @param index The rendering group index
  21216. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21217. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21218. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21219. */
  21220. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21221. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21222. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21223. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21224. this.index = index;
  21225. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21226. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21227. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21228. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21229. this._particleSystems = new BABYLON.SmartArray(256);
  21230. this._spriteManagers = new BABYLON.SmartArray(256);
  21231. this._edgesRenderers = new BABYLON.SmartArray(16);
  21232. this._scene = scene;
  21233. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21234. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21235. this.transparentSortCompareFn = transparentSortCompareFn;
  21236. }
  21237. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21238. /**
  21239. * Set the opaque sort comparison function.
  21240. * If null the sub meshes will be render in the order they were created
  21241. */
  21242. set: function (value) {
  21243. this._opaqueSortCompareFn = value;
  21244. if (value) {
  21245. this._renderOpaque = this.renderOpaqueSorted;
  21246. }
  21247. else {
  21248. this._renderOpaque = RenderingGroup.renderUnsorted;
  21249. }
  21250. },
  21251. enumerable: true,
  21252. configurable: true
  21253. });
  21254. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21255. /**
  21256. * Set the alpha test sort comparison function.
  21257. * If null the sub meshes will be render in the order they were created
  21258. */
  21259. set: function (value) {
  21260. this._alphaTestSortCompareFn = value;
  21261. if (value) {
  21262. this._renderAlphaTest = this.renderAlphaTestSorted;
  21263. }
  21264. else {
  21265. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21266. }
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21272. /**
  21273. * Set the transparent sort comparison function.
  21274. * If null the sub meshes will be render in the order they were created
  21275. */
  21276. set: function (value) {
  21277. if (value) {
  21278. this._transparentSortCompareFn = value;
  21279. }
  21280. else {
  21281. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21282. }
  21283. this._renderTransparent = this.renderTransparentSorted;
  21284. },
  21285. enumerable: true,
  21286. configurable: true
  21287. });
  21288. /**
  21289. * Render all the sub meshes contained in the group.
  21290. * @param customRenderFunction Used to override the default render behaviour of the group.
  21291. * @returns true if rendered some submeshes.
  21292. */
  21293. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21294. if (customRenderFunction) {
  21295. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21296. return;
  21297. }
  21298. var engine = this._scene.getEngine();
  21299. // Depth only
  21300. if (this._depthOnlySubMeshes.length !== 0) {
  21301. engine.setColorWrite(false);
  21302. this._renderAlphaTest(this._depthOnlySubMeshes);
  21303. engine.setColorWrite(true);
  21304. }
  21305. // Opaque
  21306. if (this._opaqueSubMeshes.length !== 0) {
  21307. this._renderOpaque(this._opaqueSubMeshes);
  21308. }
  21309. // Alpha test
  21310. if (this._alphaTestSubMeshes.length !== 0) {
  21311. this._renderAlphaTest(this._alphaTestSubMeshes);
  21312. }
  21313. var stencilState = engine.getStencilBuffer();
  21314. engine.setStencilBuffer(false);
  21315. // Sprites
  21316. if (renderSprites) {
  21317. this._renderSprites();
  21318. }
  21319. // Particles
  21320. if (renderParticles) {
  21321. this._renderParticles(activeMeshes);
  21322. }
  21323. if (this.onBeforeTransparentRendering) {
  21324. this.onBeforeTransparentRendering();
  21325. }
  21326. // Transparent
  21327. if (this._transparentSubMeshes.length !== 0) {
  21328. this._renderTransparent(this._transparentSubMeshes);
  21329. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21330. }
  21331. // Set back stencil to false in case it changes before the edge renderer.
  21332. engine.setStencilBuffer(false);
  21333. // Edges
  21334. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21335. this._edgesRenderers.data[edgesRendererIndex].render();
  21336. }
  21337. // Restore Stencil state.
  21338. engine.setStencilBuffer(stencilState);
  21339. };
  21340. /**
  21341. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21342. * @param subMeshes The submeshes to render
  21343. */
  21344. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21345. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21346. };
  21347. /**
  21348. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21349. * @param subMeshes The submeshes to render
  21350. */
  21351. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21352. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21353. };
  21354. /**
  21355. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21356. * @param subMeshes The submeshes to render
  21357. */
  21358. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21359. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21360. };
  21361. /**
  21362. * Renders the submeshes in a specified order.
  21363. * @param subMeshes The submeshes to sort before render
  21364. * @param sortCompareFn The comparison function use to sort
  21365. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21366. * @param transparent Specifies to activate blending if true
  21367. */
  21368. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21369. var subIndex = 0;
  21370. var subMesh;
  21371. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21372. for (; subIndex < subMeshes.length; subIndex++) {
  21373. subMesh = subMeshes.data[subIndex];
  21374. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21375. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21376. }
  21377. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21378. if (sortCompareFn) {
  21379. sortedArray.sort(sortCompareFn);
  21380. }
  21381. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21382. subMesh = sortedArray[subIndex];
  21383. if (transparent) {
  21384. var material = subMesh.getMaterial();
  21385. if (material && material.needDepthPrePass) {
  21386. var engine = material.getScene().getEngine();
  21387. engine.setColorWrite(false);
  21388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21389. subMesh.render(false);
  21390. engine.setColorWrite(true);
  21391. }
  21392. }
  21393. subMesh.render(transparent);
  21394. }
  21395. };
  21396. /**
  21397. * Renders the submeshes in the order they were dispatched (no sort applied).
  21398. * @param subMeshes The submeshes to render
  21399. */
  21400. RenderingGroup.renderUnsorted = function (subMeshes) {
  21401. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21402. var submesh = subMeshes.data[subIndex];
  21403. submesh.render(false);
  21404. }
  21405. };
  21406. /**
  21407. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21408. * are rendered back to front if in the same alpha index.
  21409. *
  21410. * @param a The first submesh
  21411. * @param b The second submesh
  21412. * @returns The result of the comparison
  21413. */
  21414. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21415. // Alpha index first
  21416. if (a._alphaIndex > b._alphaIndex) {
  21417. return 1;
  21418. }
  21419. if (a._alphaIndex < b._alphaIndex) {
  21420. return -1;
  21421. }
  21422. // Then distance to camera
  21423. return RenderingGroup.backToFrontSortCompare(a, b);
  21424. };
  21425. /**
  21426. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21427. * are rendered back to front.
  21428. *
  21429. * @param a The first submesh
  21430. * @param b The second submesh
  21431. * @returns The result of the comparison
  21432. */
  21433. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21434. // Then distance to camera
  21435. if (a._distanceToCamera < b._distanceToCamera) {
  21436. return 1;
  21437. }
  21438. if (a._distanceToCamera > b._distanceToCamera) {
  21439. return -1;
  21440. }
  21441. return 0;
  21442. };
  21443. /**
  21444. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21445. * are rendered front to back (prevent overdraw).
  21446. *
  21447. * @param a The first submesh
  21448. * @param b The second submesh
  21449. * @returns The result of the comparison
  21450. */
  21451. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21452. // Then distance to camera
  21453. if (a._distanceToCamera < b._distanceToCamera) {
  21454. return -1;
  21455. }
  21456. if (a._distanceToCamera > b._distanceToCamera) {
  21457. return 1;
  21458. }
  21459. return 0;
  21460. };
  21461. /**
  21462. * Resets the different lists of submeshes to prepare a new frame.
  21463. */
  21464. RenderingGroup.prototype.prepare = function () {
  21465. this._opaqueSubMeshes.reset();
  21466. this._transparentSubMeshes.reset();
  21467. this._alphaTestSubMeshes.reset();
  21468. this._depthOnlySubMeshes.reset();
  21469. this._particleSystems.reset();
  21470. this._spriteManagers.reset();
  21471. this._edgesRenderers.reset();
  21472. };
  21473. RenderingGroup.prototype.dispose = function () {
  21474. this._opaqueSubMeshes.dispose();
  21475. this._transparentSubMeshes.dispose();
  21476. this._alphaTestSubMeshes.dispose();
  21477. this._depthOnlySubMeshes.dispose();
  21478. this._particleSystems.dispose();
  21479. this._spriteManagers.dispose();
  21480. this._edgesRenderers.dispose();
  21481. };
  21482. /**
  21483. * Inserts the submesh in its correct queue depending on its material.
  21484. * @param subMesh The submesh to dispatch
  21485. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21486. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21487. */
  21488. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21489. // Get mesh and materials if not provided
  21490. if (mesh === undefined) {
  21491. mesh = subMesh.getMesh();
  21492. }
  21493. if (material === undefined) {
  21494. material = subMesh.getMaterial();
  21495. }
  21496. if (material === null || material === undefined) {
  21497. return;
  21498. }
  21499. if (material.needAlphaBlendingForMesh(mesh)) {
  21500. this._transparentSubMeshes.push(subMesh);
  21501. }
  21502. else if (material.needAlphaTesting()) {
  21503. if (material.needDepthPrePass) {
  21504. this._depthOnlySubMeshes.push(subMesh);
  21505. }
  21506. this._alphaTestSubMeshes.push(subMesh);
  21507. }
  21508. else {
  21509. if (material.needDepthPrePass) {
  21510. this._depthOnlySubMeshes.push(subMesh);
  21511. }
  21512. this._opaqueSubMeshes.push(subMesh); // Opaque
  21513. }
  21514. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21515. this._edgesRenderers.push(mesh._edgesRenderer);
  21516. }
  21517. };
  21518. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21519. this._spriteManagers.push(spriteManager);
  21520. };
  21521. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21522. this._particleSystems.push(particleSystem);
  21523. };
  21524. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21525. if (this._particleSystems.length === 0) {
  21526. return;
  21527. }
  21528. // Particles
  21529. var activeCamera = this._scene.activeCamera;
  21530. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21531. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21532. var particleSystem = this._particleSystems.data[particleIndex];
  21533. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21534. continue;
  21535. }
  21536. var emitter = particleSystem.emitter;
  21537. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21538. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21539. }
  21540. }
  21541. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21542. };
  21543. RenderingGroup.prototype._renderSprites = function () {
  21544. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21545. return;
  21546. }
  21547. // Sprites
  21548. var activeCamera = this._scene.activeCamera;
  21549. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21550. for (var id = 0; id < this._spriteManagers.length; id++) {
  21551. var spriteManager = this._spriteManagers.data[id];
  21552. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21553. spriteManager.render();
  21554. }
  21555. }
  21556. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21557. };
  21558. return RenderingGroup;
  21559. }());
  21560. BABYLON.RenderingGroup = RenderingGroup;
  21561. })(BABYLON || (BABYLON = {}));
  21562. //# sourceMappingURL=babylon.renderingGroup.js.map
  21563. "use strict";
  21564. var BABYLON;
  21565. (function (BABYLON) {
  21566. var ClickInfo = /** @class */ (function () {
  21567. function ClickInfo() {
  21568. this._singleClick = false;
  21569. this._doubleClick = false;
  21570. this._hasSwiped = false;
  21571. this._ignore = false;
  21572. }
  21573. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21574. get: function () {
  21575. return this._singleClick;
  21576. },
  21577. set: function (b) {
  21578. this._singleClick = b;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21584. get: function () {
  21585. return this._doubleClick;
  21586. },
  21587. set: function (b) {
  21588. this._doubleClick = b;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21594. get: function () {
  21595. return this._hasSwiped;
  21596. },
  21597. set: function (b) {
  21598. this._hasSwiped = b;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21604. get: function () {
  21605. return this._ignore;
  21606. },
  21607. set: function (b) {
  21608. this._ignore = b;
  21609. },
  21610. enumerable: true,
  21611. configurable: true
  21612. });
  21613. return ClickInfo;
  21614. }());
  21615. /**
  21616. * This class is used by the onRenderingGroupObservable
  21617. */
  21618. var RenderingGroupInfo = /** @class */ (function () {
  21619. function RenderingGroupInfo() {
  21620. }
  21621. /**
  21622. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21623. * This stage will be fired no matter what
  21624. */
  21625. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21626. /**
  21627. * Called before opaque object are rendered.
  21628. * This stage will be fired only if there's 3D Opaque content to render
  21629. */
  21630. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21631. /**
  21632. * Called after the opaque objects are rendered and before the transparent ones
  21633. * This stage will be fired only if there's 3D transparent content to render
  21634. */
  21635. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21636. /**
  21637. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21638. * This stage will be fired no matter what
  21639. */
  21640. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21641. return RenderingGroupInfo;
  21642. }());
  21643. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21644. /**
  21645. * Represents a scene to be rendered by the engine.
  21646. * @see http://doc.babylonjs.com/page.php?p=21911
  21647. */
  21648. var Scene = /** @class */ (function () {
  21649. /**
  21650. * @constructor
  21651. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21652. */
  21653. function Scene(engine) {
  21654. // Members
  21655. this.autoClear = true;
  21656. this.autoClearDepthAndStencil = true;
  21657. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21658. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21659. this._forceWireframe = false;
  21660. this._forcePointsCloud = false;
  21661. this.forceShowBoundingBoxes = false;
  21662. this.animationsEnabled = true;
  21663. this.useConstantAnimationDeltaTime = false;
  21664. this.constantlyUpdateMeshUnderPointer = false;
  21665. this.hoverCursor = "pointer";
  21666. this.defaultCursor = "";
  21667. /**
  21668. * This is used to call preventDefault() on pointer down
  21669. * in order to block unwanted artifacts like system double clicks
  21670. */
  21671. this.preventDefaultOnPointerDown = true;
  21672. // Metadata
  21673. this.metadata = null;
  21674. /**
  21675. * Use this array to add regular expressions used to disable offline support for specific urls
  21676. */
  21677. this.disableOfflineSupportExceptionRules = new Array();
  21678. /**
  21679. * An event triggered when the scene is disposed.
  21680. * @type {BABYLON.Observable}
  21681. */
  21682. this.onDisposeObservable = new BABYLON.Observable();
  21683. this._onDisposeObserver = null;
  21684. /**
  21685. * An event triggered before rendering the scene (right after animations and physics)
  21686. * @type {BABYLON.Observable}
  21687. */
  21688. this.onBeforeRenderObservable = new BABYLON.Observable();
  21689. this._onBeforeRenderObserver = null;
  21690. /**
  21691. * An event triggered after rendering the scene
  21692. * @type {BABYLON.Observable}
  21693. */
  21694. this.onAfterRenderObservable = new BABYLON.Observable();
  21695. this._onAfterRenderObserver = null;
  21696. /**
  21697. * An event triggered before animating the scene
  21698. * @type {BABYLON.Observable}
  21699. */
  21700. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered after animations processing
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered before draw calls are ready to be sent
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered after draw calls have been sent
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21716. /**
  21717. * An event triggered when physic simulation is about to be run
  21718. * @type {BABYLON.Observable}
  21719. */
  21720. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21721. /**
  21722. * An event triggered when physic simulation has been done
  21723. * @type {BABYLON.Observable}
  21724. */
  21725. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21726. /**
  21727. * An event triggered when the scene is ready
  21728. * @type {BABYLON.Observable}
  21729. */
  21730. this.onReadyObservable = new BABYLON.Observable();
  21731. /**
  21732. * An event triggered before rendering a camera
  21733. * @type {BABYLON.Observable}
  21734. */
  21735. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21736. this._onBeforeCameraRenderObserver = null;
  21737. /**
  21738. * An event triggered after rendering a camera
  21739. * @type {BABYLON.Observable}
  21740. */
  21741. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21742. this._onAfterCameraRenderObserver = null;
  21743. /**
  21744. * An event triggered when active meshes evaluation is about to start
  21745. * @type {BABYLON.Observable}
  21746. */
  21747. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21748. /**
  21749. * An event triggered when active meshes evaluation is done
  21750. * @type {BABYLON.Observable}
  21751. */
  21752. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21753. /**
  21754. * An event triggered when particles rendering is about to start
  21755. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21756. * @type {BABYLON.Observable}
  21757. */
  21758. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21759. /**
  21760. * An event triggered when particles rendering is done
  21761. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21762. * @type {BABYLON.Observable}
  21763. */
  21764. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21765. /**
  21766. * An event triggered when sprites rendering is about to start
  21767. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21768. * @type {BABYLON.Observable}
  21769. */
  21770. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21771. /**
  21772. * An event triggered when sprites rendering is done
  21773. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21774. * @type {BABYLON.Observable}
  21775. */
  21776. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21777. /**
  21778. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21779. * @type {BABYLON.Observable}
  21780. */
  21781. this.onDataLoadedObservable = new BABYLON.Observable();
  21782. /**
  21783. * An event triggered when a camera is created
  21784. * @type {BABYLON.Observable}
  21785. */
  21786. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21787. /**
  21788. * An event triggered when a camera is removed
  21789. * @type {BABYLON.Observable}
  21790. */
  21791. this.onCameraRemovedObservable = new BABYLON.Observable();
  21792. /**
  21793. * An event triggered when a light is created
  21794. * @type {BABYLON.Observable}
  21795. */
  21796. this.onNewLightAddedObservable = new BABYLON.Observable();
  21797. /**
  21798. * An event triggered when a light is removed
  21799. * @type {BABYLON.Observable}
  21800. */
  21801. this.onLightRemovedObservable = new BABYLON.Observable();
  21802. /**
  21803. * An event triggered when a geometry is created
  21804. * @type {BABYLON.Observable}
  21805. */
  21806. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21807. /**
  21808. * An event triggered when a geometry is removed
  21809. * @type {BABYLON.Observable}
  21810. */
  21811. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21812. /**
  21813. * An event triggered when a transform node is created
  21814. * @type {BABYLON.Observable}
  21815. */
  21816. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21817. /**
  21818. * An event triggered when a transform node is removed
  21819. * @type {BABYLON.Observable}
  21820. */
  21821. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21822. /**
  21823. * An event triggered when a mesh is created
  21824. * @type {BABYLON.Observable}
  21825. */
  21826. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21827. /**
  21828. * An event triggered when a mesh is removed
  21829. * @type {BABYLON.Observable}
  21830. */
  21831. this.onMeshRemovedObservable = new BABYLON.Observable();
  21832. /**
  21833. * An event triggered when render targets are about to be rendered
  21834. * Can happen multiple times per frame.
  21835. * @type {BABYLON.Observable}
  21836. */
  21837. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21838. /**
  21839. * An event triggered when render targets were rendered.
  21840. * Can happen multiple times per frame.
  21841. * @type {BABYLON.Observable}
  21842. */
  21843. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21844. /**
  21845. * An event triggered before calculating deterministic simulation step
  21846. * @type {BABYLON.Observable}
  21847. */
  21848. this.onBeforeStepObservable = new BABYLON.Observable();
  21849. /**
  21850. * An event triggered after calculating deterministic simulation step
  21851. * @type {BABYLON.Observable}
  21852. */
  21853. this.onAfterStepObservable = new BABYLON.Observable();
  21854. /**
  21855. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21856. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21857. * 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)
  21858. */
  21859. this.onRenderingGroupObservable = new BABYLON.Observable();
  21860. // Animations
  21861. this.animations = [];
  21862. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21863. /**
  21864. * 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).
  21865. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21866. */
  21867. this.onPrePointerObservable = new BABYLON.Observable();
  21868. /**
  21869. * Observable event triggered each time an input event is received from the rendering canvas
  21870. */
  21871. this.onPointerObservable = new BABYLON.Observable();
  21872. this._meshPickProceed = false;
  21873. this._currentPickResult = null;
  21874. this._previousPickResult = null;
  21875. this._totalPointersPressed = 0;
  21876. this._doubleClickOccured = false;
  21877. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21878. this.cameraToUseForPointers = null;
  21879. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21880. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21881. this._startingPointerTime = 0;
  21882. this._previousStartingPointerTime = 0;
  21883. // Deterministic lockstep
  21884. this._timeAccumulator = 0;
  21885. this._currentStepId = 0;
  21886. this._currentInternalStep = 0;
  21887. // Keyboard
  21888. /**
  21889. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21890. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21891. */
  21892. this.onPreKeyboardObservable = new BABYLON.Observable();
  21893. /**
  21894. * Observable event triggered each time an keyboard event is received from the hosting window
  21895. */
  21896. this.onKeyboardObservable = new BABYLON.Observable();
  21897. // Coordinate system
  21898. /**
  21899. * use right-handed coordinate system on this scene.
  21900. * @type {boolean}
  21901. */
  21902. this._useRightHandedSystem = false;
  21903. // Fog
  21904. this._fogEnabled = true;
  21905. this._fogMode = Scene.FOGMODE_NONE;
  21906. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21907. this.fogDensity = 0.1;
  21908. this.fogStart = 0;
  21909. this.fogEnd = 1000.0;
  21910. // Lights
  21911. /**
  21912. * is shadow enabled on this scene.
  21913. * @type {boolean}
  21914. */
  21915. this._shadowsEnabled = true;
  21916. /**
  21917. * is light enabled on this scene.
  21918. * @type {boolean}
  21919. */
  21920. this._lightsEnabled = true;
  21921. /**
  21922. * All of the lights added to this scene.
  21923. */
  21924. this.lights = new Array();
  21925. // Cameras
  21926. /** All of the cameras added to this scene. */
  21927. this.cameras = new Array();
  21928. /** All of the active cameras added to this scene. */
  21929. this.activeCameras = new Array();
  21930. // Meshes
  21931. /**
  21932. * All of the tranform nodes added to this scene.
  21933. */
  21934. this.transformNodes = new Array();
  21935. /**
  21936. * All of the (abstract) meshes added to this scene.
  21937. */
  21938. this.meshes = new Array();
  21939. /**
  21940. * All of the animation groups added to this scene.
  21941. */
  21942. this.animationGroups = new Array();
  21943. // Geometries
  21944. this._geometries = new Array();
  21945. this.materials = new Array();
  21946. this.multiMaterials = new Array();
  21947. // Textures
  21948. this._texturesEnabled = true;
  21949. this.textures = new Array();
  21950. // Particles
  21951. this.particlesEnabled = true;
  21952. this.particleSystems = new Array();
  21953. // Sprites
  21954. this.spritesEnabled = true;
  21955. this.spriteManagers = new Array();
  21956. /**
  21957. * The list of layers (background and foreground) of the scene.
  21958. */
  21959. this.layers = new Array();
  21960. /**
  21961. * The list of effect layers (highlights/glow) contained in the scene.
  21962. */
  21963. this.effectLayers = new Array();
  21964. // Skeletons
  21965. this._skeletonsEnabled = true;
  21966. this.skeletons = new Array();
  21967. // Morph targets
  21968. this.morphTargetManagers = new Array();
  21969. // Lens flares
  21970. this.lensFlaresEnabled = true;
  21971. this.lensFlareSystems = new Array();
  21972. // Collisions
  21973. this.collisionsEnabled = true;
  21974. /** Defines the gravity applied to this scene */
  21975. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21976. // Postprocesses
  21977. this.postProcesses = new Array();
  21978. this.postProcessesEnabled = true;
  21979. // Customs render targets
  21980. this.renderTargetsEnabled = true;
  21981. this.dumpNextRenderTargets = false;
  21982. this.customRenderTargets = new Array();
  21983. // Imported meshes
  21984. this.importedMeshesFiles = new Array();
  21985. // Probes
  21986. this.probesEnabled = true;
  21987. this.reflectionProbes = new Array();
  21988. this._actionManagers = new Array();
  21989. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21990. // Procedural textures
  21991. this.proceduralTexturesEnabled = true;
  21992. this._proceduralTextures = new Array();
  21993. this.soundTracks = new Array();
  21994. this._audioEnabled = true;
  21995. this._headphone = false;
  21996. // Performance counters
  21997. this._totalVertices = new BABYLON.PerfCounter();
  21998. this._activeIndices = new BABYLON.PerfCounter();
  21999. this._activeParticles = new BABYLON.PerfCounter();
  22000. this._activeBones = new BABYLON.PerfCounter();
  22001. this._animationTime = 0;
  22002. this.animationTimeScale = 1;
  22003. this._renderId = 0;
  22004. this._executeWhenReadyTimeoutId = -1;
  22005. this._intermediateRendering = false;
  22006. this._viewUpdateFlag = -1;
  22007. this._projectionUpdateFlag = -1;
  22008. this._alternateViewUpdateFlag = -1;
  22009. this._alternateProjectionUpdateFlag = -1;
  22010. this._toBeDisposed = new BABYLON.SmartArray(256);
  22011. this._activeRequests = new Array();
  22012. this._pendingData = new Array();
  22013. this._isDisposed = false;
  22014. this.dispatchAllSubMeshesOfActiveMeshes = false;
  22015. this._activeMeshes = new BABYLON.SmartArray(256);
  22016. this._processedMaterials = new BABYLON.SmartArray(256);
  22017. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  22018. this._activeParticleSystems = new BABYLON.SmartArray(256);
  22019. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  22020. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  22021. this._activeAnimatables = new Array();
  22022. this._transformMatrix = BABYLON.Matrix.Zero();
  22023. this._useAlternateCameraConfiguration = false;
  22024. this._alternateRendering = false;
  22025. this.requireLightSorting = false;
  22026. this._depthRenderer = {};
  22027. this._activeMeshesFrozen = false;
  22028. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  22029. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  22030. this._engine.scenes.push(this);
  22031. this._uid = null;
  22032. this._renderingManager = new BABYLON.RenderingManager(this);
  22033. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22034. if (BABYLON.OutlineRenderer) {
  22035. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22036. }
  22037. if (BABYLON.Tools.IsWindowObjectExist()) {
  22038. this.attachControl();
  22039. }
  22040. //simplification queue
  22041. if (BABYLON.SimplificationQueue) {
  22042. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22043. }
  22044. //collision coordinator initialization. For now legacy per default.
  22045. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22046. // Uniform Buffer
  22047. this._createUbo();
  22048. // Default Image processing definition.
  22049. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22050. }
  22051. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22052. /** The fog is deactivated */
  22053. get: function () {
  22054. return Scene._FOGMODE_NONE;
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22060. /** The fog density is following an exponential function */
  22061. get: function () {
  22062. return Scene._FOGMODE_EXP;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22068. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22069. get: function () {
  22070. return Scene._FOGMODE_EXP2;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22076. /** The fog density is following a linear function. */
  22077. get: function () {
  22078. return Scene._FOGMODE_LINEAR;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22084. /**
  22085. * Texture used in all pbr material as the reflection texture.
  22086. * As in the majority of the scene they are the same (exception for multi room and so on),
  22087. * this is easier to reference from here than from all the materials.
  22088. */
  22089. get: function () {
  22090. return this._environmentTexture;
  22091. },
  22092. /**
  22093. * Texture used in all pbr material as the reflection texture.
  22094. * As in the majority of the scene they are the same (exception for multi room and so on),
  22095. * this is easier to set here than in all the materials.
  22096. */
  22097. set: function (value) {
  22098. if (this._environmentTexture === value) {
  22099. return;
  22100. }
  22101. this._environmentTexture = value;
  22102. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22103. },
  22104. enumerable: true,
  22105. configurable: true
  22106. });
  22107. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22108. /**
  22109. * Default image processing configuration used either in the rendering
  22110. * Forward main pass or through the imageProcessingPostProcess if present.
  22111. * As in the majority of the scene they are the same (exception for multi camera),
  22112. * this is easier to reference from here than from all the materials and post process.
  22113. *
  22114. * No setter as we it is a shared configuration, you can set the values instead.
  22115. */
  22116. get: function () {
  22117. return this._imageProcessingConfiguration;
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22123. get: function () {
  22124. return this._forceWireframe;
  22125. },
  22126. set: function (value) {
  22127. if (this._forceWireframe === value) {
  22128. return;
  22129. }
  22130. this._forceWireframe = value;
  22131. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22137. get: function () {
  22138. return this._forcePointsCloud;
  22139. },
  22140. set: function (value) {
  22141. if (this._forcePointsCloud === value) {
  22142. return;
  22143. }
  22144. this._forcePointsCloud = value;
  22145. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Object.defineProperty(Scene.prototype, "onDispose", {
  22151. /** A function to be executed when this scene is disposed. */
  22152. set: function (callback) {
  22153. if (this._onDisposeObserver) {
  22154. this.onDisposeObservable.remove(this._onDisposeObserver);
  22155. }
  22156. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. Object.defineProperty(Scene.prototype, "beforeRender", {
  22162. /** A function to be executed before rendering this scene */
  22163. set: function (callback) {
  22164. if (this._onBeforeRenderObserver) {
  22165. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22166. }
  22167. if (callback) {
  22168. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22169. }
  22170. },
  22171. enumerable: true,
  22172. configurable: true
  22173. });
  22174. Object.defineProperty(Scene.prototype, "afterRender", {
  22175. /** A function to be executed after rendering this scene */
  22176. set: function (callback) {
  22177. if (this._onAfterRenderObserver) {
  22178. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22179. }
  22180. if (callback) {
  22181. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22182. }
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22188. set: function (callback) {
  22189. if (this._onBeforeCameraRenderObserver) {
  22190. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22191. }
  22192. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22193. },
  22194. enumerable: true,
  22195. configurable: true
  22196. });
  22197. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22198. set: function (callback) {
  22199. if (this._onAfterCameraRenderObserver) {
  22200. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22201. }
  22202. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22208. get: function () {
  22209. if (!this._gamepadManager) {
  22210. this._gamepadManager = new BABYLON.GamepadManager(this);
  22211. }
  22212. return this._gamepadManager;
  22213. },
  22214. enumerable: true,
  22215. configurable: true
  22216. });
  22217. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22218. get: function () {
  22219. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22220. },
  22221. enumerable: true,
  22222. configurable: true
  22223. });
  22224. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22225. get: function () {
  22226. return this._useRightHandedSystem;
  22227. },
  22228. set: function (value) {
  22229. if (this._useRightHandedSystem === value) {
  22230. return;
  22231. }
  22232. this._useRightHandedSystem = value;
  22233. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22234. },
  22235. enumerable: true,
  22236. configurable: true
  22237. });
  22238. Scene.prototype.setStepId = function (newStepId) {
  22239. this._currentStepId = newStepId;
  22240. };
  22241. ;
  22242. Scene.prototype.getStepId = function () {
  22243. return this._currentStepId;
  22244. };
  22245. ;
  22246. Scene.prototype.getInternalStep = function () {
  22247. return this._currentInternalStep;
  22248. };
  22249. ;
  22250. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22251. get: function () {
  22252. return this._fogEnabled;
  22253. },
  22254. /**
  22255. * is fog enabled on this scene.
  22256. */
  22257. set: function (value) {
  22258. if (this._fogEnabled === value) {
  22259. return;
  22260. }
  22261. this._fogEnabled = value;
  22262. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. Object.defineProperty(Scene.prototype, "fogMode", {
  22268. get: function () {
  22269. return this._fogMode;
  22270. },
  22271. set: function (value) {
  22272. if (this._fogMode === value) {
  22273. return;
  22274. }
  22275. this._fogMode = value;
  22276. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22282. get: function () {
  22283. return this._shadowsEnabled;
  22284. },
  22285. set: function (value) {
  22286. if (this._shadowsEnabled === value) {
  22287. return;
  22288. }
  22289. this._shadowsEnabled = value;
  22290. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22296. get: function () {
  22297. return this._lightsEnabled;
  22298. },
  22299. set: function (value) {
  22300. if (this._lightsEnabled === value) {
  22301. return;
  22302. }
  22303. this._lightsEnabled = value;
  22304. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22310. /** The default material used on meshes when no material is affected */
  22311. get: function () {
  22312. if (!this._defaultMaterial) {
  22313. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22314. }
  22315. return this._defaultMaterial;
  22316. },
  22317. /** The default material used on meshes when no material is affected */
  22318. set: function (value) {
  22319. this._defaultMaterial = value;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22325. get: function () {
  22326. return this._texturesEnabled;
  22327. },
  22328. set: function (value) {
  22329. if (this._texturesEnabled === value) {
  22330. return;
  22331. }
  22332. this._texturesEnabled = value;
  22333. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22334. },
  22335. enumerable: true,
  22336. configurable: true
  22337. });
  22338. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22339. get: function () {
  22340. return this._skeletonsEnabled;
  22341. },
  22342. set: function (value) {
  22343. if (this._skeletonsEnabled === value) {
  22344. return;
  22345. }
  22346. this._skeletonsEnabled = value;
  22347. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22348. },
  22349. enumerable: true,
  22350. configurable: true
  22351. });
  22352. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22353. get: function () {
  22354. if (!this._postProcessRenderPipelineManager) {
  22355. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22356. }
  22357. return this._postProcessRenderPipelineManager;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22363. get: function () {
  22364. if (!this._mainSoundTrack) {
  22365. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22366. }
  22367. return this._mainSoundTrack;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22373. get: function () {
  22374. return this._alternateRendering;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22380. get: function () {
  22381. return this._frustumPlanes;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22387. /**
  22388. * Gets the current geometry buffer associated to the scene.
  22389. */
  22390. get: function () {
  22391. return this._geometryBufferRenderer;
  22392. },
  22393. /**
  22394. * Sets the current geometry buffer for the scene.
  22395. */
  22396. set: function (geometryBufferRenderer) {
  22397. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22398. this._geometryBufferRenderer = geometryBufferRenderer;
  22399. }
  22400. },
  22401. enumerable: true,
  22402. configurable: true
  22403. });
  22404. Object.defineProperty(Scene.prototype, "debugLayer", {
  22405. // Properties
  22406. get: function () {
  22407. if (!this._debugLayer) {
  22408. this._debugLayer = new BABYLON.DebugLayer(this);
  22409. }
  22410. return this._debugLayer;
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22416. get: function () {
  22417. return this._workerCollisions;
  22418. },
  22419. set: function (enabled) {
  22420. if (!BABYLON.CollisionCoordinatorLegacy) {
  22421. return;
  22422. }
  22423. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22424. this._workerCollisions = enabled;
  22425. if (this.collisionCoordinator) {
  22426. this.collisionCoordinator.destroy();
  22427. }
  22428. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22429. this.collisionCoordinator.init(this);
  22430. },
  22431. enumerable: true,
  22432. configurable: true
  22433. });
  22434. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22435. get: function () {
  22436. return this._selectionOctree;
  22437. },
  22438. enumerable: true,
  22439. configurable: true
  22440. });
  22441. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22442. /**
  22443. * The mesh that is currently under the pointer.
  22444. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22445. */
  22446. get: function () {
  22447. return this._pointerOverMesh;
  22448. },
  22449. enumerable: true,
  22450. configurable: true
  22451. });
  22452. Object.defineProperty(Scene.prototype, "pointerX", {
  22453. /**
  22454. * Current on-screen X position of the pointer
  22455. * @return {number} X position of the pointer
  22456. */
  22457. get: function () {
  22458. return this._pointerX;
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. Object.defineProperty(Scene.prototype, "pointerY", {
  22464. /**
  22465. * Current on-screen Y position of the pointer
  22466. * @return {number} Y position of the pointer
  22467. */
  22468. get: function () {
  22469. return this._pointerY;
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. Scene.prototype.getCachedMaterial = function () {
  22475. return this._cachedMaterial;
  22476. };
  22477. Scene.prototype.getCachedEffect = function () {
  22478. return this._cachedEffect;
  22479. };
  22480. Scene.prototype.getCachedVisibility = function () {
  22481. return this._cachedVisibility;
  22482. };
  22483. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22484. if (visibility === void 0) { visibility = 1; }
  22485. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22486. };
  22487. Scene.prototype.getBoundingBoxRenderer = function () {
  22488. if (!this._boundingBoxRenderer) {
  22489. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22490. }
  22491. return this._boundingBoxRenderer;
  22492. };
  22493. Scene.prototype.getOutlineRenderer = function () {
  22494. return this._outlineRenderer;
  22495. };
  22496. Scene.prototype.getEngine = function () {
  22497. return this._engine;
  22498. };
  22499. Scene.prototype.getTotalVertices = function () {
  22500. return this._totalVertices.current;
  22501. };
  22502. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22503. get: function () {
  22504. return this._totalVertices;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Scene.prototype.getActiveIndices = function () {
  22510. return this._activeIndices.current;
  22511. };
  22512. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22513. get: function () {
  22514. return this._activeIndices;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. Scene.prototype.getActiveParticles = function () {
  22520. return this._activeParticles.current;
  22521. };
  22522. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22523. get: function () {
  22524. return this._activeParticles;
  22525. },
  22526. enumerable: true,
  22527. configurable: true
  22528. });
  22529. Scene.prototype.getActiveBones = function () {
  22530. return this._activeBones.current;
  22531. };
  22532. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22533. get: function () {
  22534. return this._activeBones;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. // Stats
  22540. Scene.prototype.getInterFramePerfCounter = function () {
  22541. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22542. return 0;
  22543. };
  22544. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22545. get: function () {
  22546. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22547. return null;
  22548. },
  22549. enumerable: true,
  22550. configurable: true
  22551. });
  22552. Scene.prototype.getLastFrameDuration = function () {
  22553. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22554. return 0;
  22555. };
  22556. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22557. get: function () {
  22558. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22559. return null;
  22560. },
  22561. enumerable: true,
  22562. configurable: true
  22563. });
  22564. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22565. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22566. return 0;
  22567. };
  22568. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22569. get: function () {
  22570. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22571. return null;
  22572. },
  22573. enumerable: true,
  22574. configurable: true
  22575. });
  22576. Scene.prototype.getActiveMeshes = function () {
  22577. return this._activeMeshes;
  22578. };
  22579. Scene.prototype.getRenderTargetsDuration = function () {
  22580. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22581. return 0;
  22582. };
  22583. Scene.prototype.getRenderDuration = function () {
  22584. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22585. return 0;
  22586. };
  22587. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22588. get: function () {
  22589. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22590. return null;
  22591. },
  22592. enumerable: true,
  22593. configurable: true
  22594. });
  22595. Scene.prototype.getParticlesDuration = function () {
  22596. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22597. return 0;
  22598. };
  22599. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22600. get: function () {
  22601. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22602. return null;
  22603. },
  22604. enumerable: true,
  22605. configurable: true
  22606. });
  22607. Scene.prototype.getSpritesDuration = function () {
  22608. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22609. return 0;
  22610. };
  22611. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22612. get: function () {
  22613. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22614. return null;
  22615. },
  22616. enumerable: true,
  22617. configurable: true
  22618. });
  22619. Scene.prototype.getAnimationRatio = function () {
  22620. return this._animationRatio;
  22621. };
  22622. Scene.prototype.getRenderId = function () {
  22623. return this._renderId;
  22624. };
  22625. Scene.prototype.incrementRenderId = function () {
  22626. this._renderId++;
  22627. };
  22628. Scene.prototype._updatePointerPosition = function (evt) {
  22629. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22630. if (!canvasRect) {
  22631. return;
  22632. }
  22633. this._pointerX = evt.clientX - canvasRect.left;
  22634. this._pointerY = evt.clientY - canvasRect.top;
  22635. this._unTranslatedPointerX = this._pointerX;
  22636. this._unTranslatedPointerY = this._pointerY;
  22637. };
  22638. Scene.prototype._createUbo = function () {
  22639. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22640. this._sceneUbo.addUniform("viewProjection", 16);
  22641. this._sceneUbo.addUniform("view", 16);
  22642. };
  22643. Scene.prototype._createAlternateUbo = function () {
  22644. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22645. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22646. this._alternateSceneUbo.addUniform("view", 16);
  22647. };
  22648. // Pointers handling
  22649. /**
  22650. * Use this method to simulate a pointer move on a mesh
  22651. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22652. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22653. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22654. */
  22655. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22656. var evt = new PointerEvent("pointermove", pointerEventInit);
  22657. return this._processPointerMove(pickResult, evt);
  22658. };
  22659. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22660. var canvas = this._engine.getRenderingCanvas();
  22661. if (!canvas) {
  22662. return this;
  22663. }
  22664. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22665. this.setPointerOverSprite(null);
  22666. this.setPointerOverMesh(pickResult.pickedMesh);
  22667. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22668. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22669. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22670. }
  22671. else {
  22672. canvas.style.cursor = this.hoverCursor;
  22673. }
  22674. }
  22675. else {
  22676. canvas.style.cursor = this.defaultCursor;
  22677. }
  22678. }
  22679. else {
  22680. this.setPointerOverMesh(null);
  22681. // Sprites
  22682. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22683. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22684. this.setPointerOverSprite(pickResult.pickedSprite);
  22685. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22686. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22687. }
  22688. else {
  22689. canvas.style.cursor = this.hoverCursor;
  22690. }
  22691. }
  22692. else {
  22693. this.setPointerOverSprite(null);
  22694. // Restore pointer
  22695. canvas.style.cursor = this.defaultCursor;
  22696. }
  22697. }
  22698. if (pickResult) {
  22699. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22700. if (this.onPointerMove) {
  22701. this.onPointerMove(evt, pickResult, type);
  22702. }
  22703. if (this.onPointerObservable.hasObservers()) {
  22704. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22705. this.onPointerObservable.notifyObservers(pi, type);
  22706. }
  22707. }
  22708. return this;
  22709. };
  22710. /**
  22711. * Use this method to simulate a pointer down on a mesh
  22712. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22713. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22714. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22715. */
  22716. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22717. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22718. return this._processPointerDown(pickResult, evt);
  22719. };
  22720. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22721. var _this = this;
  22722. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22723. this._pickedDownMesh = pickResult.pickedMesh;
  22724. var actionManager = pickResult.pickedMesh.actionManager;
  22725. if (actionManager) {
  22726. if (actionManager.hasPickTriggers) {
  22727. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22728. switch (evt.button) {
  22729. case 0:
  22730. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22731. break;
  22732. case 1:
  22733. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22734. break;
  22735. case 2:
  22736. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22737. break;
  22738. }
  22739. }
  22740. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22741. window.setTimeout(function () {
  22742. 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);
  22743. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22744. if (_this._totalPointersPressed !== 0 &&
  22745. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22746. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22747. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22748. _this._startingPointerTime = 0;
  22749. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22750. }
  22751. }
  22752. }, Scene.LongPressDelay);
  22753. }
  22754. }
  22755. }
  22756. if (pickResult) {
  22757. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22758. if (this.onPointerDown) {
  22759. this.onPointerDown(evt, pickResult, type);
  22760. }
  22761. if (this.onPointerObservable.hasObservers()) {
  22762. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22763. this.onPointerObservable.notifyObservers(pi, type);
  22764. }
  22765. }
  22766. return this;
  22767. };
  22768. /**
  22769. * Use this method to simulate a pointer up on a mesh
  22770. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22771. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22772. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22773. */
  22774. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22775. var evt = new PointerEvent("pointerup", pointerEventInit);
  22776. var clickInfo = new ClickInfo();
  22777. clickInfo.singleClick = true;
  22778. clickInfo.ignore = true;
  22779. return this._processPointerUp(pickResult, evt, clickInfo);
  22780. };
  22781. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22782. if (pickResult && pickResult && pickResult.pickedMesh) {
  22783. this._pickedUpMesh = pickResult.pickedMesh;
  22784. if (this._pickedDownMesh === this._pickedUpMesh) {
  22785. if (this.onPointerPick) {
  22786. this.onPointerPick(evt, pickResult);
  22787. }
  22788. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22789. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22790. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22791. this.onPointerObservable.notifyObservers(pi, type_1);
  22792. }
  22793. }
  22794. if (pickResult.pickedMesh.actionManager) {
  22795. if (clickInfo.ignore) {
  22796. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22797. }
  22798. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22799. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22800. }
  22801. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22802. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22803. }
  22804. }
  22805. }
  22806. if (this._pickedDownMesh &&
  22807. this._pickedDownMesh.actionManager &&
  22808. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22809. this._pickedDownMesh !== this._pickedUpMesh) {
  22810. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22811. }
  22812. var type = BABYLON.PointerEventTypes.POINTERUP;
  22813. if (this.onPointerObservable.hasObservers()) {
  22814. if (!clickInfo.ignore) {
  22815. if (!clickInfo.hasSwiped) {
  22816. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22817. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22818. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22819. this.onPointerObservable.notifyObservers(pi, type_2);
  22820. }
  22821. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22822. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22823. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22824. this.onPointerObservable.notifyObservers(pi, type_3);
  22825. }
  22826. }
  22827. }
  22828. else {
  22829. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22830. this.onPointerObservable.notifyObservers(pi, type);
  22831. }
  22832. }
  22833. if (this.onPointerUp) {
  22834. this.onPointerUp(evt, pickResult, type);
  22835. }
  22836. return this;
  22837. };
  22838. /**
  22839. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22840. * @param attachUp defines if you want to attach events to pointerup
  22841. * @param attachDown defines if you want to attach events to pointerdown
  22842. * @param attachMove defines if you want to attach events to pointermove
  22843. */
  22844. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22845. var _this = this;
  22846. if (attachUp === void 0) { attachUp = true; }
  22847. if (attachDown === void 0) { attachDown = true; }
  22848. if (attachMove === void 0) { attachMove = true; }
  22849. this._initActionManager = function (act, clickInfo) {
  22850. if (!_this._meshPickProceed) {
  22851. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22852. _this._currentPickResult = pickResult;
  22853. if (pickResult) {
  22854. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22855. }
  22856. _this._meshPickProceed = true;
  22857. }
  22858. return act;
  22859. };
  22860. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22861. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22862. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22863. btn !== _this._previousButtonPressed) {
  22864. _this._doubleClickOccured = false;
  22865. clickInfo.singleClick = true;
  22866. clickInfo.ignore = false;
  22867. cb(clickInfo, _this._currentPickResult);
  22868. }
  22869. };
  22870. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22871. var clickInfo = new ClickInfo();
  22872. _this._currentPickResult = null;
  22873. var act = null;
  22874. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22875. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22876. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22877. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22878. act = _this._initActionManager(act, clickInfo);
  22879. if (act)
  22880. checkPicking = act.hasPickTriggers;
  22881. }
  22882. if (checkPicking) {
  22883. var btn = evt.button;
  22884. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22885. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22886. if (!clickInfo.hasSwiped) {
  22887. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22888. if (!checkSingleClickImmediately) {
  22889. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22890. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22891. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22892. act = _this._initActionManager(act, clickInfo);
  22893. if (act)
  22894. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22895. }
  22896. }
  22897. if (checkSingleClickImmediately) {
  22898. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22899. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22900. btn !== _this._previousButtonPressed) {
  22901. clickInfo.singleClick = true;
  22902. cb(clickInfo, _this._currentPickResult);
  22903. }
  22904. }
  22905. else {
  22906. // wait that no double click has been raised during the double click delay
  22907. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22908. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22909. }
  22910. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22911. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22912. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22913. act = _this._initActionManager(act, clickInfo);
  22914. if (act)
  22915. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22916. }
  22917. if (checkDoubleClick) {
  22918. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22919. if (btn === _this._previousButtonPressed &&
  22920. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22921. !_this._doubleClickOccured) {
  22922. // pointer has not moved for 2 clicks, it's a double click
  22923. if (!clickInfo.hasSwiped &&
  22924. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22925. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22926. _this._previousStartingPointerTime = 0;
  22927. _this._doubleClickOccured = true;
  22928. clickInfo.doubleClick = true;
  22929. clickInfo.ignore = false;
  22930. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22931. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22932. }
  22933. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22934. cb(clickInfo, _this._currentPickResult);
  22935. }
  22936. else {
  22937. _this._doubleClickOccured = false;
  22938. _this._previousStartingPointerTime = _this._startingPointerTime;
  22939. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22940. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22941. _this._previousButtonPressed = btn;
  22942. if (Scene.ExclusiveDoubleClickMode) {
  22943. if (_this._previousDelayedSimpleClickTimeout) {
  22944. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22945. }
  22946. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22947. cb(clickInfo, _this._previousPickResult);
  22948. }
  22949. else {
  22950. cb(clickInfo, _this._currentPickResult);
  22951. }
  22952. }
  22953. }
  22954. else {
  22955. _this._doubleClickOccured = false;
  22956. _this._previousStartingPointerTime = _this._startingPointerTime;
  22957. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22958. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22959. _this._previousButtonPressed = btn;
  22960. }
  22961. }
  22962. }
  22963. }
  22964. clickInfo.ignore = true;
  22965. cb(clickInfo, _this._currentPickResult);
  22966. };
  22967. this._spritePredicate = function (sprite) {
  22968. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22969. };
  22970. this._onPointerMove = function (evt) {
  22971. _this._updatePointerPosition(evt);
  22972. // PreObservable support
  22973. if (_this.onPrePointerObservable.hasObservers()) {
  22974. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22975. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22976. _this.onPrePointerObservable.notifyObservers(pi, type);
  22977. if (pi.skipOnPointerObservable) {
  22978. return;
  22979. }
  22980. }
  22981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22982. return;
  22983. }
  22984. if (!_this.pointerMovePredicate) {
  22985. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22986. }
  22987. // Meshes
  22988. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22989. _this._processPointerMove(pickResult, evt);
  22990. };
  22991. this._onPointerDown = function (evt) {
  22992. _this._totalPointersPressed++;
  22993. _this._pickedDownMesh = null;
  22994. _this._meshPickProceed = false;
  22995. _this._updatePointerPosition(evt);
  22996. if (_this.preventDefaultOnPointerDown && canvas) {
  22997. evt.preventDefault();
  22998. canvas.focus();
  22999. }
  23000. // PreObservable support
  23001. if (_this.onPrePointerObservable.hasObservers()) {
  23002. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  23003. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23004. _this.onPrePointerObservable.notifyObservers(pi, type);
  23005. if (pi.skipOnPointerObservable) {
  23006. return;
  23007. }
  23008. }
  23009. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23010. return;
  23011. }
  23012. _this._startingPointerPosition.x = _this._pointerX;
  23013. _this._startingPointerPosition.y = _this._pointerY;
  23014. _this._startingPointerTime = new Date().getTime();
  23015. if (!_this.pointerDownPredicate) {
  23016. _this.pointerDownPredicate = function (mesh) {
  23017. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23018. };
  23019. }
  23020. // Meshes
  23021. _this._pickedDownMesh = null;
  23022. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23023. _this._processPointerDown(pickResult, evt);
  23024. // Sprites
  23025. _this._pickedDownSprite = null;
  23026. if (_this.spriteManagers.length > 0) {
  23027. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23028. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23029. if (pickResult.pickedSprite.actionManager) {
  23030. _this._pickedDownSprite = pickResult.pickedSprite;
  23031. switch (evt.button) {
  23032. case 0:
  23033. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23034. break;
  23035. case 1:
  23036. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23037. break;
  23038. case 2:
  23039. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23040. break;
  23041. }
  23042. if (pickResult.pickedSprite.actionManager) {
  23043. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23044. }
  23045. }
  23046. }
  23047. }
  23048. };
  23049. this._onPointerUp = function (evt) {
  23050. if (_this._totalPointersPressed === 0) {
  23051. return; // So we need to test it the pointer down was pressed before.
  23052. }
  23053. _this._totalPointersPressed--;
  23054. _this._pickedUpMesh = null;
  23055. _this._meshPickProceed = false;
  23056. _this._updatePointerPosition(evt);
  23057. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23058. // PreObservable support
  23059. if (_this.onPrePointerObservable.hasObservers()) {
  23060. if (!clickInfo.ignore) {
  23061. if (!clickInfo.hasSwiped) {
  23062. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23063. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23064. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23065. _this.onPrePointerObservable.notifyObservers(pi, type);
  23066. if (pi.skipOnPointerObservable) {
  23067. return;
  23068. }
  23069. }
  23070. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23071. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23072. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23073. _this.onPrePointerObservable.notifyObservers(pi, type);
  23074. if (pi.skipOnPointerObservable) {
  23075. return;
  23076. }
  23077. }
  23078. }
  23079. }
  23080. else {
  23081. var type = BABYLON.PointerEventTypes.POINTERUP;
  23082. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23083. _this.onPrePointerObservable.notifyObservers(pi, type);
  23084. if (pi.skipOnPointerObservable) {
  23085. return;
  23086. }
  23087. }
  23088. }
  23089. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23090. return;
  23091. }
  23092. if (!_this.pointerUpPredicate) {
  23093. _this.pointerUpPredicate = function (mesh) {
  23094. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23095. };
  23096. }
  23097. // Meshes
  23098. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23099. _this._initActionManager(null, clickInfo);
  23100. }
  23101. if (!pickResult) {
  23102. pickResult = _this._currentPickResult;
  23103. }
  23104. _this._processPointerUp(pickResult, evt, clickInfo);
  23105. // Sprites
  23106. if (_this.spriteManagers.length > 0) {
  23107. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23108. if (spritePickResult) {
  23109. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23110. if (spritePickResult.pickedSprite.actionManager) {
  23111. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23112. if (spritePickResult.pickedSprite.actionManager) {
  23113. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23114. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23115. }
  23116. }
  23117. }
  23118. }
  23119. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23120. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23121. }
  23122. }
  23123. }
  23124. _this._previousPickResult = _this._currentPickResult;
  23125. });
  23126. };
  23127. this._onKeyDown = function (evt) {
  23128. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23129. if (_this.onPreKeyboardObservable.hasObservers()) {
  23130. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23131. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23132. if (pi.skipOnPointerObservable) {
  23133. return;
  23134. }
  23135. }
  23136. if (_this.onKeyboardObservable.hasObservers()) {
  23137. var pi = new BABYLON.KeyboardInfo(type, evt);
  23138. _this.onKeyboardObservable.notifyObservers(pi, type);
  23139. }
  23140. if (_this.actionManager) {
  23141. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23142. }
  23143. };
  23144. this._onKeyUp = function (evt) {
  23145. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23146. if (_this.onPreKeyboardObservable.hasObservers()) {
  23147. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23148. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23149. if (pi.skipOnPointerObservable) {
  23150. return;
  23151. }
  23152. }
  23153. if (_this.onKeyboardObservable.hasObservers()) {
  23154. var pi = new BABYLON.KeyboardInfo(type, evt);
  23155. _this.onKeyboardObservable.notifyObservers(pi, type);
  23156. }
  23157. if (_this.actionManager) {
  23158. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23159. }
  23160. };
  23161. var engine = this.getEngine();
  23162. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23163. if (!canvas) {
  23164. return;
  23165. }
  23166. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23167. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23168. });
  23169. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23170. if (!canvas) {
  23171. return;
  23172. }
  23173. canvas.removeEventListener("keydown", _this._onKeyDown);
  23174. canvas.removeEventListener("keyup", _this._onKeyUp);
  23175. });
  23176. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23177. var canvas = this._engine.getRenderingCanvas();
  23178. if (!canvas) {
  23179. return;
  23180. }
  23181. if (attachMove) {
  23182. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23183. // Wheel
  23184. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23185. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23186. }
  23187. if (attachDown) {
  23188. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23189. }
  23190. if (attachUp) {
  23191. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23192. }
  23193. canvas.tabIndex = 1;
  23194. };
  23195. Scene.prototype.detachControl = function () {
  23196. var engine = this.getEngine();
  23197. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23198. var canvas = engine.getRenderingCanvas();
  23199. if (!canvas) {
  23200. return;
  23201. }
  23202. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23203. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23204. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23205. if (this._onCanvasBlurObserver) {
  23206. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23207. }
  23208. if (this._onCanvasFocusObserver) {
  23209. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23210. }
  23211. // Wheel
  23212. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23213. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23214. // Keyboard
  23215. canvas.removeEventListener("keydown", this._onKeyDown);
  23216. canvas.removeEventListener("keyup", this._onKeyUp);
  23217. // Observables
  23218. this.onKeyboardObservable.clear();
  23219. this.onPreKeyboardObservable.clear();
  23220. this.onPointerObservable.clear();
  23221. this.onPrePointerObservable.clear();
  23222. };
  23223. /**
  23224. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23225. * Delay loaded resources are not taking in account
  23226. * @return true if all required resources are ready
  23227. */
  23228. Scene.prototype.isReady = function () {
  23229. if (this._isDisposed) {
  23230. return false;
  23231. }
  23232. if (this._pendingData.length > 0) {
  23233. return false;
  23234. }
  23235. var index;
  23236. var engine = this.getEngine();
  23237. // Geometries
  23238. for (index = 0; index < this._geometries.length; index++) {
  23239. var geometry = this._geometries[index];
  23240. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23241. return false;
  23242. }
  23243. }
  23244. // Meshes
  23245. for (index = 0; index < this.meshes.length; index++) {
  23246. var mesh = this.meshes[index];
  23247. if (!mesh.isEnabled()) {
  23248. continue;
  23249. }
  23250. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23251. continue;
  23252. }
  23253. if (!mesh.isReady(true)) {
  23254. return false;
  23255. }
  23256. // Effect layers
  23257. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23258. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23259. var layer = _a[_i];
  23260. if (!layer.hasMesh(mesh)) {
  23261. continue;
  23262. }
  23263. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23264. var subMesh = _c[_b];
  23265. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23266. return false;
  23267. }
  23268. }
  23269. }
  23270. }
  23271. // Post-processes
  23272. if (this.activeCameras && this.activeCameras.length > 0) {
  23273. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23274. var camera = _e[_d];
  23275. if (!camera.isReady(true)) {
  23276. return false;
  23277. }
  23278. }
  23279. }
  23280. else if (this.activeCamera) {
  23281. if (!this.activeCamera.isReady(true)) {
  23282. return false;
  23283. }
  23284. }
  23285. // Particles
  23286. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23287. var particleSystem = _g[_f];
  23288. if (!particleSystem.isReady()) {
  23289. return false;
  23290. }
  23291. }
  23292. return true;
  23293. };
  23294. Scene.prototype.resetCachedMaterial = function () {
  23295. this._cachedMaterial = null;
  23296. this._cachedEffect = null;
  23297. this._cachedVisibility = null;
  23298. };
  23299. Scene.prototype.registerBeforeRender = function (func) {
  23300. this.onBeforeRenderObservable.add(func);
  23301. };
  23302. Scene.prototype.unregisterBeforeRender = function (func) {
  23303. this.onBeforeRenderObservable.removeCallback(func);
  23304. };
  23305. Scene.prototype.registerAfterRender = function (func) {
  23306. this.onAfterRenderObservable.add(func);
  23307. };
  23308. Scene.prototype.unregisterAfterRender = function (func) {
  23309. this.onAfterRenderObservable.removeCallback(func);
  23310. };
  23311. Scene.prototype._executeOnceBeforeRender = function (func) {
  23312. var _this = this;
  23313. var execFunc = function () {
  23314. func();
  23315. setTimeout(function () {
  23316. _this.unregisterBeforeRender(execFunc);
  23317. });
  23318. };
  23319. this.registerBeforeRender(execFunc);
  23320. };
  23321. /**
  23322. * The provided function will run before render once and will be disposed afterwards.
  23323. * A timeout delay can be provided so that the function will be executed in N ms.
  23324. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23325. * @param func The function to be executed.
  23326. * @param timeout optional delay in ms
  23327. */
  23328. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23329. var _this = this;
  23330. if (timeout !== undefined) {
  23331. setTimeout(function () {
  23332. _this._executeOnceBeforeRender(func);
  23333. }, timeout);
  23334. }
  23335. else {
  23336. this._executeOnceBeforeRender(func);
  23337. }
  23338. };
  23339. Scene.prototype._addPendingData = function (data) {
  23340. this._pendingData.push(data);
  23341. };
  23342. Scene.prototype._removePendingData = function (data) {
  23343. var wasLoading = this.isLoading;
  23344. var index = this._pendingData.indexOf(data);
  23345. if (index !== -1) {
  23346. this._pendingData.splice(index, 1);
  23347. }
  23348. if (wasLoading && !this.isLoading) {
  23349. this.onDataLoadedObservable.notifyObservers(this);
  23350. }
  23351. };
  23352. Scene.prototype.getWaitingItemsCount = function () {
  23353. return this._pendingData.length;
  23354. };
  23355. Object.defineProperty(Scene.prototype, "isLoading", {
  23356. get: function () {
  23357. return this._pendingData.length > 0;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. /**
  23363. * Registers a function to be executed when the scene is ready.
  23364. * @param {Function} func - the function to be executed.
  23365. */
  23366. Scene.prototype.executeWhenReady = function (func) {
  23367. var _this = this;
  23368. this.onReadyObservable.add(func);
  23369. if (this._executeWhenReadyTimeoutId !== -1) {
  23370. return;
  23371. }
  23372. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23373. _this._checkIsReady();
  23374. }, 150);
  23375. };
  23376. /**
  23377. * Returns a promise that resolves when the scene is ready.
  23378. * @returns A promise that resolves when the scene is ready.
  23379. */
  23380. Scene.prototype.whenReadyAsync = function () {
  23381. var _this = this;
  23382. return new Promise(function (resolve) {
  23383. _this.executeWhenReady(function () {
  23384. resolve();
  23385. });
  23386. });
  23387. };
  23388. Scene.prototype._checkIsReady = function () {
  23389. var _this = this;
  23390. if (this.isReady()) {
  23391. this.onReadyObservable.notifyObservers(this);
  23392. this.onReadyObservable.clear();
  23393. this._executeWhenReadyTimeoutId = -1;
  23394. return;
  23395. }
  23396. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23397. _this._checkIsReady();
  23398. }, 150);
  23399. };
  23400. // Animations
  23401. /**
  23402. * Will start the animation sequence of a given target
  23403. * @param target defines the target
  23404. * @param from defines from which frame should animation start
  23405. * @param to defines until which frame should animation run.
  23406. * @param weight defines the weight to apply to the animation (1.0 by default)
  23407. * @param loop defines if the animation loops
  23408. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23409. * @param onAnimationEnd defines the function to be executed when the animation ends
  23410. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23411. * @returns the animatable object created for this animation
  23412. */
  23413. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23414. if (weight === void 0) { weight = 1.0; }
  23415. if (speedRatio === void 0) { speedRatio = 1.0; }
  23416. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23417. returnedAnimatable.weight = weight;
  23418. return returnedAnimatable;
  23419. };
  23420. /**
  23421. * Will start the animation sequence of a given target
  23422. * @param target defines the target
  23423. * @param from defines from which frame should animation start
  23424. * @param to defines until which frame should animation run.
  23425. * @param loop defines if the animation loops
  23426. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23427. * @param onAnimationEnd defines the function to be executed when the animation ends
  23428. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23429. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23430. * @returns the animatable object created for this animation
  23431. */
  23432. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23433. if (speedRatio === void 0) { speedRatio = 1.0; }
  23434. if (stopCurrent === void 0) { stopCurrent = true; }
  23435. if (from > to && speedRatio > 0) {
  23436. speedRatio *= -1;
  23437. }
  23438. if (stopCurrent) {
  23439. this.stopAnimation(target);
  23440. }
  23441. if (!animatable) {
  23442. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23443. }
  23444. // Local animations
  23445. if (target.animations) {
  23446. animatable.appendAnimations(target, target.animations);
  23447. }
  23448. // Children animations
  23449. if (target.getAnimatables) {
  23450. var animatables = target.getAnimatables();
  23451. for (var index = 0; index < animatables.length; index++) {
  23452. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23453. }
  23454. }
  23455. animatable.reset();
  23456. return animatable;
  23457. };
  23458. /**
  23459. * Begin a new animation on a given node
  23460. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23461. * @param {BABYLON.Animation[]} defines the list of animations to start
  23462. * @param {number} from defines the initial value
  23463. * @param {number} to defines the final value
  23464. * @param {boolean} loop defines if you want animation to loop (off by default)
  23465. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23466. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23467. * @returns the list of created animatables
  23468. */
  23469. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23470. if (speedRatio === undefined) {
  23471. speedRatio = 1.0;
  23472. }
  23473. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23474. return animatable;
  23475. };
  23476. /**
  23477. * Begin a new animation on a given node and its hierarchy
  23478. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23479. * @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.
  23480. * @param {BABYLON.Animation[]} defines the list of animations to start
  23481. * @param {number} from defines the initial value
  23482. * @param {number} to defines the final value
  23483. * @param {boolean} loop defines if you want animation to loop (off by default)
  23484. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23485. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23486. * @returns the list of animatables created for all nodes
  23487. */
  23488. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23489. var children = target.getDescendants(directDescendantsOnly);
  23490. var result = [];
  23491. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23492. var child = children_1[_i];
  23493. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23494. }
  23495. return result;
  23496. };
  23497. Scene.prototype.getAnimatableByTarget = function (target) {
  23498. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23499. if (this._activeAnimatables[index].target === target) {
  23500. return this._activeAnimatables[index];
  23501. }
  23502. }
  23503. return null;
  23504. };
  23505. /**
  23506. * Gets all animatables associated with a given target
  23507. * @param target defines the target to look animatables for
  23508. * @returns an array of Animatables
  23509. */
  23510. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23511. var result = [];
  23512. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23513. if (this._activeAnimatables[index].target === target) {
  23514. result.push(this._activeAnimatables[index]);
  23515. }
  23516. }
  23517. return result;
  23518. };
  23519. Object.defineProperty(Scene.prototype, "animatables", {
  23520. get: function () {
  23521. return this._activeAnimatables;
  23522. },
  23523. enumerable: true,
  23524. configurable: true
  23525. });
  23526. /**
  23527. * Will stop the animation of the given target
  23528. * @param target - the target
  23529. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23530. */
  23531. Scene.prototype.stopAnimation = function (target, animationName) {
  23532. var animatables = this.getAllAnimatablesByTarget(target);
  23533. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23534. var animatable = animatables_1[_i];
  23535. animatable.stop(animationName);
  23536. }
  23537. };
  23538. /**
  23539. * Stops and removes all animations that have been applied to the scene
  23540. */
  23541. Scene.prototype.stopAllAnimations = function () {
  23542. if (this._activeAnimatables) {
  23543. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23544. this._activeAnimatables[i].stop();
  23545. }
  23546. this._activeAnimatables = [];
  23547. }
  23548. };
  23549. Scene.prototype._animate = function () {
  23550. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23551. return;
  23552. }
  23553. // Getting time
  23554. var now = BABYLON.Tools.Now;
  23555. if (!this._animationTimeLast) {
  23556. if (this._pendingData.length > 0) {
  23557. return;
  23558. }
  23559. this._animationTimeLast = now;
  23560. }
  23561. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23562. this._animationTime += deltaTime;
  23563. this._animationTimeLast = now;
  23564. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23565. this._activeAnimatables[index]._animate(this._animationTime);
  23566. }
  23567. // Late animation bindings
  23568. this._processLateAnimationBindings();
  23569. };
  23570. /** @ignore */
  23571. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23572. var target = runtimeAnimation.target;
  23573. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23574. if (!target._lateAnimationHolders) {
  23575. target._lateAnimationHolders = {};
  23576. }
  23577. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23578. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23579. totalWeight: 0,
  23580. animations: []
  23581. };
  23582. }
  23583. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23584. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23585. };
  23586. Scene.prototype._processLateAnimationBindings = function () {
  23587. if (!this._registeredForLateAnimationBindings.length) {
  23588. return;
  23589. }
  23590. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23591. var target = this._registeredForLateAnimationBindings.data[index];
  23592. for (var path in target._lateAnimationHolders) {
  23593. var holder = target._lateAnimationHolders[path];
  23594. // Sanity check
  23595. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23596. continue;
  23597. }
  23598. var normalizer = 1.0;
  23599. var finalValue = void 0;
  23600. if (holder.totalWeight < 1.0) {
  23601. // We need to mix the original value in
  23602. var originalValue = holder.animations[0].originalValue;
  23603. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23604. }
  23605. else {
  23606. // We need to normalize the weights
  23607. normalizer = holder.totalWeight;
  23608. }
  23609. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23610. var runtimeAnimation = holder.animations[animIndex];
  23611. if (finalValue) {
  23612. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23613. }
  23614. else {
  23615. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23616. }
  23617. }
  23618. runtimeAnimation.target[path] = finalValue;
  23619. }
  23620. target._lateAnimationHolders = {};
  23621. }
  23622. this._registeredForLateAnimationBindings.reset();
  23623. };
  23624. // Matrix
  23625. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23626. this._useAlternateCameraConfiguration = active;
  23627. };
  23628. Scene.prototype.getViewMatrix = function () {
  23629. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23630. };
  23631. Scene.prototype.getProjectionMatrix = function () {
  23632. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23633. };
  23634. Scene.prototype.getTransformMatrix = function () {
  23635. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23636. };
  23637. Scene.prototype.setTransformMatrix = function (view, projection) {
  23638. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23639. return;
  23640. }
  23641. this._viewUpdateFlag = view.updateFlag;
  23642. this._projectionUpdateFlag = projection.updateFlag;
  23643. this._viewMatrix = view;
  23644. this._projectionMatrix = projection;
  23645. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23646. // Update frustum
  23647. if (!this._frustumPlanes) {
  23648. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23649. }
  23650. else {
  23651. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23652. }
  23653. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23654. var otherCamera = this.activeCamera._alternateCamera;
  23655. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23656. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23657. }
  23658. if (this._sceneUbo.useUbo) {
  23659. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23660. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23661. this._sceneUbo.update();
  23662. }
  23663. };
  23664. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23665. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23666. return;
  23667. }
  23668. this._alternateViewUpdateFlag = view.updateFlag;
  23669. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23670. this._alternateViewMatrix = view;
  23671. this._alternateProjectionMatrix = projection;
  23672. if (!this._alternateTransformMatrix) {
  23673. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23674. }
  23675. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23676. if (!this._alternateSceneUbo) {
  23677. this._createAlternateUbo();
  23678. }
  23679. if (this._alternateSceneUbo.useUbo) {
  23680. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23681. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23682. this._alternateSceneUbo.update();
  23683. }
  23684. };
  23685. Scene.prototype.getSceneUniformBuffer = function () {
  23686. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23687. };
  23688. // Methods
  23689. Scene.prototype.getUniqueId = function () {
  23690. var result = Scene._uniqueIdCounter;
  23691. Scene._uniqueIdCounter++;
  23692. return result;
  23693. };
  23694. Scene.prototype.addMesh = function (newMesh) {
  23695. this.meshes.push(newMesh);
  23696. //notify the collision coordinator
  23697. if (this.collisionCoordinator) {
  23698. this.collisionCoordinator.onMeshAdded(newMesh);
  23699. }
  23700. newMesh._resyncLightSources();
  23701. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23702. };
  23703. Scene.prototype.removeMesh = function (toRemove) {
  23704. var index = this.meshes.indexOf(toRemove);
  23705. if (index !== -1) {
  23706. // Remove from the scene if mesh found
  23707. this.meshes.splice(index, 1);
  23708. }
  23709. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23710. return index;
  23711. };
  23712. Scene.prototype.addTransformNode = function (newTransformNode) {
  23713. this.transformNodes.push(newTransformNode);
  23714. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23715. };
  23716. Scene.prototype.removeTransformNode = function (toRemove) {
  23717. var index = this.transformNodes.indexOf(toRemove);
  23718. if (index !== -1) {
  23719. // Remove from the scene if found
  23720. this.transformNodes.splice(index, 1);
  23721. }
  23722. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23723. return index;
  23724. };
  23725. Scene.prototype.removeSkeleton = function (toRemove) {
  23726. var index = this.skeletons.indexOf(toRemove);
  23727. if (index !== -1) {
  23728. // Remove from the scene if found
  23729. this.skeletons.splice(index, 1);
  23730. }
  23731. return index;
  23732. };
  23733. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23734. var index = this.morphTargetManagers.indexOf(toRemove);
  23735. if (index !== -1) {
  23736. // Remove from the scene if found
  23737. this.morphTargetManagers.splice(index, 1);
  23738. }
  23739. return index;
  23740. };
  23741. Scene.prototype.removeLight = function (toRemove) {
  23742. var index = this.lights.indexOf(toRemove);
  23743. if (index !== -1) {
  23744. // Remove from meshes
  23745. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23746. var mesh = _a[_i];
  23747. mesh._removeLightSource(toRemove);
  23748. }
  23749. // Remove from the scene if mesh found
  23750. this.lights.splice(index, 1);
  23751. this.sortLightsByPriority();
  23752. }
  23753. this.onLightRemovedObservable.notifyObservers(toRemove);
  23754. return index;
  23755. };
  23756. Scene.prototype.removeCamera = function (toRemove) {
  23757. var index = this.cameras.indexOf(toRemove);
  23758. if (index !== -1) {
  23759. // Remove from the scene if mesh found
  23760. this.cameras.splice(index, 1);
  23761. }
  23762. // Remove from activeCameras
  23763. var index2 = this.activeCameras.indexOf(toRemove);
  23764. if (index2 !== -1) {
  23765. // Remove from the scene if mesh found
  23766. this.activeCameras.splice(index2, 1);
  23767. }
  23768. // Reset the activeCamera
  23769. if (this.activeCamera === toRemove) {
  23770. if (this.cameras.length > 0) {
  23771. this.activeCamera = this.cameras[0];
  23772. }
  23773. else {
  23774. this.activeCamera = null;
  23775. }
  23776. }
  23777. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23778. return index;
  23779. };
  23780. Scene.prototype.removeParticleSystem = function (toRemove) {
  23781. var index = this.particleSystems.indexOf(toRemove);
  23782. if (index !== -1) {
  23783. this.particleSystems.splice(index, 1);
  23784. }
  23785. return index;
  23786. };
  23787. ;
  23788. Scene.prototype.removeAnimation = function (toRemove) {
  23789. var index = this.animations.indexOf(toRemove);
  23790. if (index !== -1) {
  23791. this.animations.splice(index, 1);
  23792. }
  23793. return index;
  23794. };
  23795. ;
  23796. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23797. var index = this.multiMaterials.indexOf(toRemove);
  23798. if (index !== -1) {
  23799. this.multiMaterials.splice(index, 1);
  23800. }
  23801. return index;
  23802. };
  23803. ;
  23804. Scene.prototype.removeMaterial = function (toRemove) {
  23805. var index = this.materials.indexOf(toRemove);
  23806. if (index !== -1) {
  23807. this.materials.splice(index, 1);
  23808. }
  23809. return index;
  23810. };
  23811. ;
  23812. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23813. var index = this.lensFlareSystems.indexOf(toRemove);
  23814. if (index !== -1) {
  23815. this.lensFlareSystems.splice(index, 1);
  23816. }
  23817. return index;
  23818. };
  23819. ;
  23820. Scene.prototype.removeActionManager = function (toRemove) {
  23821. var index = this._actionManagers.indexOf(toRemove);
  23822. if (index !== -1) {
  23823. this._actionManagers.splice(index, 1);
  23824. }
  23825. return index;
  23826. };
  23827. ;
  23828. Scene.prototype.addLight = function (newLight) {
  23829. this.lights.push(newLight);
  23830. this.sortLightsByPriority();
  23831. // Add light to all meshes (To support if the light is removed and then readded)
  23832. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23833. var mesh = _a[_i];
  23834. if (mesh._lightSources.indexOf(newLight) === -1) {
  23835. mesh._lightSources.push(newLight);
  23836. mesh._resyncLightSources();
  23837. }
  23838. }
  23839. this.onNewLightAddedObservable.notifyObservers(newLight);
  23840. };
  23841. Scene.prototype.sortLightsByPriority = function () {
  23842. if (this.requireLightSorting) {
  23843. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23844. }
  23845. };
  23846. Scene.prototype.addCamera = function (newCamera) {
  23847. this.cameras.push(newCamera);
  23848. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23849. };
  23850. Scene.prototype.addSkeleton = function (newSkeleton) {
  23851. this.skeletons.push(newSkeleton);
  23852. };
  23853. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23854. this.particleSystems.push(newParticleSystem);
  23855. };
  23856. Scene.prototype.addAnimation = function (newAnimation) {
  23857. this.animations.push(newAnimation);
  23858. };
  23859. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23860. this.multiMaterials.push(newMultiMaterial);
  23861. };
  23862. Scene.prototype.addMaterial = function (newMaterial) {
  23863. this.materials.push(newMaterial);
  23864. };
  23865. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23866. this.morphTargetManagers.push(newMorphTargetManager);
  23867. };
  23868. Scene.prototype.addGeometry = function (newGeometrie) {
  23869. this._geometries.push(newGeometrie);
  23870. };
  23871. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23872. this.lensFlareSystems.push(newLensFlareSystem);
  23873. };
  23874. Scene.prototype.addActionManager = function (newActionManager) {
  23875. this._actionManagers.push(newActionManager);
  23876. };
  23877. /**
  23878. * Switch active camera
  23879. * @param {Camera} newCamera - new active camera
  23880. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23881. */
  23882. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23883. if (attachControl === void 0) { attachControl = true; }
  23884. var canvas = this._engine.getRenderingCanvas();
  23885. if (!canvas) {
  23886. return;
  23887. }
  23888. if (this.activeCamera) {
  23889. this.activeCamera.detachControl(canvas);
  23890. }
  23891. this.activeCamera = newCamera;
  23892. if (attachControl) {
  23893. newCamera.attachControl(canvas);
  23894. }
  23895. };
  23896. /**
  23897. * sets the active camera of the scene using its ID
  23898. * @param {string} id - the camera's ID
  23899. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23900. */
  23901. Scene.prototype.setActiveCameraByID = function (id) {
  23902. var camera = this.getCameraByID(id);
  23903. if (camera) {
  23904. this.activeCamera = camera;
  23905. return camera;
  23906. }
  23907. return null;
  23908. };
  23909. /**
  23910. * sets the active camera of the scene using its name
  23911. * @param {string} name - the camera's name
  23912. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23913. */
  23914. Scene.prototype.setActiveCameraByName = function (name) {
  23915. var camera = this.getCameraByName(name);
  23916. if (camera) {
  23917. this.activeCamera = camera;
  23918. return camera;
  23919. }
  23920. return null;
  23921. };
  23922. /**
  23923. * get an animation group using its name
  23924. * @param {string} the material's name
  23925. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23926. */
  23927. Scene.prototype.getAnimationGroupByName = function (name) {
  23928. for (var index = 0; index < this.animationGroups.length; index++) {
  23929. if (this.animationGroups[index].name === name) {
  23930. return this.animationGroups[index];
  23931. }
  23932. }
  23933. return null;
  23934. };
  23935. /**
  23936. * get a material using its id
  23937. * @param {string} the material's ID
  23938. * @return {BABYLON.Material|null} the material or null if none found.
  23939. */
  23940. Scene.prototype.getMaterialByID = function (id) {
  23941. for (var index = 0; index < this.materials.length; index++) {
  23942. if (this.materials[index].id === id) {
  23943. return this.materials[index];
  23944. }
  23945. }
  23946. return null;
  23947. };
  23948. /**
  23949. * get a material using its name
  23950. * @param {string} the material's name
  23951. * @return {BABYLON.Material|null} the material or null if none found.
  23952. */
  23953. Scene.prototype.getMaterialByName = function (name) {
  23954. for (var index = 0; index < this.materials.length; index++) {
  23955. if (this.materials[index].name === name) {
  23956. return this.materials[index];
  23957. }
  23958. }
  23959. return null;
  23960. };
  23961. Scene.prototype.getLensFlareSystemByName = function (name) {
  23962. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23963. if (this.lensFlareSystems[index].name === name) {
  23964. return this.lensFlareSystems[index];
  23965. }
  23966. }
  23967. return null;
  23968. };
  23969. Scene.prototype.getLensFlareSystemByID = function (id) {
  23970. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23971. if (this.lensFlareSystems[index].id === id) {
  23972. return this.lensFlareSystems[index];
  23973. }
  23974. }
  23975. return null;
  23976. };
  23977. Scene.prototype.getCameraByID = function (id) {
  23978. for (var index = 0; index < this.cameras.length; index++) {
  23979. if (this.cameras[index].id === id) {
  23980. return this.cameras[index];
  23981. }
  23982. }
  23983. return null;
  23984. };
  23985. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23986. for (var index = 0; index < this.cameras.length; index++) {
  23987. if (this.cameras[index].uniqueId === uniqueId) {
  23988. return this.cameras[index];
  23989. }
  23990. }
  23991. return null;
  23992. };
  23993. /**
  23994. * get a camera using its name
  23995. * @param {string} the camera's name
  23996. * @return {BABYLON.Camera|null} the camera or null if none found.
  23997. */
  23998. Scene.prototype.getCameraByName = function (name) {
  23999. for (var index = 0; index < this.cameras.length; index++) {
  24000. if (this.cameras[index].name === name) {
  24001. return this.cameras[index];
  24002. }
  24003. }
  24004. return null;
  24005. };
  24006. /**
  24007. * get a bone using its id
  24008. * @param {string} the bone's id
  24009. * @return {BABYLON.Bone|null} the bone or null if not found
  24010. */
  24011. Scene.prototype.getBoneByID = function (id) {
  24012. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24013. var skeleton = this.skeletons[skeletonIndex];
  24014. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24015. if (skeleton.bones[boneIndex].id === id) {
  24016. return skeleton.bones[boneIndex];
  24017. }
  24018. }
  24019. }
  24020. return null;
  24021. };
  24022. /**
  24023. * get a bone using its id
  24024. * @param {string} the bone's name
  24025. * @return {BABYLON.Bone|null} the bone or null if not found
  24026. */
  24027. Scene.prototype.getBoneByName = function (name) {
  24028. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24029. var skeleton = this.skeletons[skeletonIndex];
  24030. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24031. if (skeleton.bones[boneIndex].name === name) {
  24032. return skeleton.bones[boneIndex];
  24033. }
  24034. }
  24035. }
  24036. return null;
  24037. };
  24038. /**
  24039. * get a light node using its name
  24040. * @param {string} the light's name
  24041. * @return {BABYLON.Light|null} the light or null if none found.
  24042. */
  24043. Scene.prototype.getLightByName = function (name) {
  24044. for (var index = 0; index < this.lights.length; index++) {
  24045. if (this.lights[index].name === name) {
  24046. return this.lights[index];
  24047. }
  24048. }
  24049. return null;
  24050. };
  24051. /**
  24052. * get a light node using its ID
  24053. * @param {string} the light's id
  24054. * @return {BABYLON.Light|null} the light or null if none found.
  24055. */
  24056. Scene.prototype.getLightByID = function (id) {
  24057. for (var index = 0; index < this.lights.length; index++) {
  24058. if (this.lights[index].id === id) {
  24059. return this.lights[index];
  24060. }
  24061. }
  24062. return null;
  24063. };
  24064. /**
  24065. * get a light node using its scene-generated unique ID
  24066. * @param {number} the light's unique id
  24067. * @return {BABYLON.Light|null} the light or null if none found.
  24068. */
  24069. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24070. for (var index = 0; index < this.lights.length; index++) {
  24071. if (this.lights[index].uniqueId === uniqueId) {
  24072. return this.lights[index];
  24073. }
  24074. }
  24075. return null;
  24076. };
  24077. /**
  24078. * get a particle system by id
  24079. * @param id {number} the particle system id
  24080. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  24081. */
  24082. Scene.prototype.getParticleSystemByID = function (id) {
  24083. for (var index = 0; index < this.particleSystems.length; index++) {
  24084. if (this.particleSystems[index].id === id) {
  24085. return this.particleSystems[index];
  24086. }
  24087. }
  24088. return null;
  24089. };
  24090. /**
  24091. * get a geometry using its ID
  24092. * @param {string} the geometry's id
  24093. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24094. */
  24095. Scene.prototype.getGeometryByID = function (id) {
  24096. for (var index = 0; index < this._geometries.length; index++) {
  24097. if (this._geometries[index].id === id) {
  24098. return this._geometries[index];
  24099. }
  24100. }
  24101. return null;
  24102. };
  24103. /**
  24104. * add a new geometry to this scene.
  24105. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24106. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24107. * @return {boolean} was the geometry added or not
  24108. */
  24109. Scene.prototype.pushGeometry = function (geometry, force) {
  24110. if (!force && this.getGeometryByID(geometry.id)) {
  24111. return false;
  24112. }
  24113. this._geometries.push(geometry);
  24114. //notify the collision coordinator
  24115. if (this.collisionCoordinator) {
  24116. this.collisionCoordinator.onGeometryAdded(geometry);
  24117. }
  24118. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24119. return true;
  24120. };
  24121. /**
  24122. * Removes an existing geometry
  24123. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24124. * @return {boolean} was the geometry removed or not
  24125. */
  24126. Scene.prototype.removeGeometry = function (geometry) {
  24127. var index = this._geometries.indexOf(geometry);
  24128. if (index > -1) {
  24129. this._geometries.splice(index, 1);
  24130. //notify the collision coordinator
  24131. if (this.collisionCoordinator) {
  24132. this.collisionCoordinator.onGeometryDeleted(geometry);
  24133. }
  24134. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24135. return true;
  24136. }
  24137. return false;
  24138. };
  24139. Scene.prototype.getGeometries = function () {
  24140. return this._geometries;
  24141. };
  24142. /**
  24143. * Get the first added mesh found of a given ID
  24144. * @param {string} id - the id to search for
  24145. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24146. */
  24147. Scene.prototype.getMeshByID = function (id) {
  24148. for (var index = 0; index < this.meshes.length; index++) {
  24149. if (this.meshes[index].id === id) {
  24150. return this.meshes[index];
  24151. }
  24152. }
  24153. return null;
  24154. };
  24155. Scene.prototype.getMeshesByID = function (id) {
  24156. return this.meshes.filter(function (m) {
  24157. return m.id === id;
  24158. });
  24159. };
  24160. /**
  24161. * Get the first added transform node found of a given ID
  24162. * @param {string} id - the id to search for
  24163. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24164. */
  24165. Scene.prototype.getTransformNodeByID = function (id) {
  24166. for (var index = 0; index < this.transformNodes.length; index++) {
  24167. if (this.transformNodes[index].id === id) {
  24168. return this.transformNodes[index];
  24169. }
  24170. }
  24171. return null;
  24172. };
  24173. Scene.prototype.getTransformNodesByID = function (id) {
  24174. return this.transformNodes.filter(function (m) {
  24175. return m.id === id;
  24176. });
  24177. };
  24178. /**
  24179. * Get a mesh with its auto-generated unique id
  24180. * @param {number} uniqueId - the unique id to search for
  24181. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24182. */
  24183. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24184. for (var index = 0; index < this.meshes.length; index++) {
  24185. if (this.meshes[index].uniqueId === uniqueId) {
  24186. return this.meshes[index];
  24187. }
  24188. }
  24189. return null;
  24190. };
  24191. /**
  24192. * Get a the last added mesh found of a given ID
  24193. * @param {string} id - the id to search for
  24194. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24195. */
  24196. Scene.prototype.getLastMeshByID = function (id) {
  24197. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24198. if (this.meshes[index].id === id) {
  24199. return this.meshes[index];
  24200. }
  24201. }
  24202. return null;
  24203. };
  24204. /**
  24205. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24206. * @param {string} id - the id to search for
  24207. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24208. */
  24209. Scene.prototype.getLastEntryByID = function (id) {
  24210. var index;
  24211. for (index = this.meshes.length - 1; index >= 0; index--) {
  24212. if (this.meshes[index].id === id) {
  24213. return this.meshes[index];
  24214. }
  24215. }
  24216. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24217. if (this.transformNodes[index].id === id) {
  24218. return this.transformNodes[index];
  24219. }
  24220. }
  24221. for (index = this.cameras.length - 1; index >= 0; index--) {
  24222. if (this.cameras[index].id === id) {
  24223. return this.cameras[index];
  24224. }
  24225. }
  24226. for (index = this.lights.length - 1; index >= 0; index--) {
  24227. if (this.lights[index].id === id) {
  24228. return this.lights[index];
  24229. }
  24230. }
  24231. return null;
  24232. };
  24233. Scene.prototype.getNodeByID = function (id) {
  24234. var mesh = this.getMeshByID(id);
  24235. if (mesh) {
  24236. return mesh;
  24237. }
  24238. var light = this.getLightByID(id);
  24239. if (light) {
  24240. return light;
  24241. }
  24242. var camera = this.getCameraByID(id);
  24243. if (camera) {
  24244. return camera;
  24245. }
  24246. var bone = this.getBoneByID(id);
  24247. return bone;
  24248. };
  24249. Scene.prototype.getNodeByName = function (name) {
  24250. var mesh = this.getMeshByName(name);
  24251. if (mesh) {
  24252. return mesh;
  24253. }
  24254. var light = this.getLightByName(name);
  24255. if (light) {
  24256. return light;
  24257. }
  24258. var camera = this.getCameraByName(name);
  24259. if (camera) {
  24260. return camera;
  24261. }
  24262. var bone = this.getBoneByName(name);
  24263. return bone;
  24264. };
  24265. Scene.prototype.getMeshByName = function (name) {
  24266. for (var index = 0; index < this.meshes.length; index++) {
  24267. if (this.meshes[index].name === name) {
  24268. return this.meshes[index];
  24269. }
  24270. }
  24271. return null;
  24272. };
  24273. Scene.prototype.getTransformNodeByName = function (name) {
  24274. for (var index = 0; index < this.transformNodes.length; index++) {
  24275. if (this.transformNodes[index].name === name) {
  24276. return this.transformNodes[index];
  24277. }
  24278. }
  24279. return null;
  24280. };
  24281. Scene.prototype.getSoundByName = function (name) {
  24282. var index;
  24283. if (BABYLON.AudioEngine) {
  24284. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24285. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24286. return this.mainSoundTrack.soundCollection[index];
  24287. }
  24288. }
  24289. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24290. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24291. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24292. return this.soundTracks[sdIndex].soundCollection[index];
  24293. }
  24294. }
  24295. }
  24296. }
  24297. return null;
  24298. };
  24299. Scene.prototype.getLastSkeletonByID = function (id) {
  24300. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24301. if (this.skeletons[index].id === id) {
  24302. return this.skeletons[index];
  24303. }
  24304. }
  24305. return null;
  24306. };
  24307. Scene.prototype.getSkeletonById = function (id) {
  24308. for (var index = 0; index < this.skeletons.length; index++) {
  24309. if (this.skeletons[index].id === id) {
  24310. return this.skeletons[index];
  24311. }
  24312. }
  24313. return null;
  24314. };
  24315. Scene.prototype.getSkeletonByName = function (name) {
  24316. for (var index = 0; index < this.skeletons.length; index++) {
  24317. if (this.skeletons[index].name === name) {
  24318. return this.skeletons[index];
  24319. }
  24320. }
  24321. return null;
  24322. };
  24323. Scene.prototype.getMorphTargetManagerById = function (id) {
  24324. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24325. if (this.morphTargetManagers[index].uniqueId === id) {
  24326. return this.morphTargetManagers[index];
  24327. }
  24328. }
  24329. return null;
  24330. };
  24331. Scene.prototype.isActiveMesh = function (mesh) {
  24332. return (this._activeMeshes.indexOf(mesh) !== -1);
  24333. };
  24334. /**
  24335. * Return a the first highlight layer of the scene with a given name.
  24336. * @param name The name of the highlight layer to look for.
  24337. * @return The highlight layer if found otherwise null.
  24338. */
  24339. Scene.prototype.getHighlightLayerByName = function (name) {
  24340. for (var index = 0; index < this.effectLayers.length; index++) {
  24341. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24342. return this.effectLayers[index];
  24343. }
  24344. }
  24345. return null;
  24346. };
  24347. /**
  24348. * Return a the first highlight layer of the scene with a given name.
  24349. * @param name The name of the highlight layer to look for.
  24350. * @return The highlight layer if found otherwise null.
  24351. */
  24352. Scene.prototype.getGlowLayerByName = function (name) {
  24353. for (var index = 0; index < this.effectLayers.length; index++) {
  24354. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24355. return this.effectLayers[index];
  24356. }
  24357. }
  24358. return null;
  24359. };
  24360. Object.defineProperty(Scene.prototype, "uid", {
  24361. /**
  24362. * Return a unique id as a string which can serve as an identifier for the scene
  24363. */
  24364. get: function () {
  24365. if (!this._uid) {
  24366. this._uid = BABYLON.Tools.RandomId();
  24367. }
  24368. return this._uid;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. /**
  24374. * Add an externaly attached data from its key.
  24375. * This method call will fail and return false, if such key already exists.
  24376. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24377. * @param key the unique key that identifies the data
  24378. * @param data the data object to associate to the key for this Engine instance
  24379. * @return true if no such key were already present and the data was added successfully, false otherwise
  24380. */
  24381. Scene.prototype.addExternalData = function (key, data) {
  24382. if (!this._externalData) {
  24383. this._externalData = new BABYLON.StringDictionary();
  24384. }
  24385. return this._externalData.add(key, data);
  24386. };
  24387. /**
  24388. * Get an externaly attached data from its key
  24389. * @param key the unique key that identifies the data
  24390. * @return the associated data, if present (can be null), or undefined if not present
  24391. */
  24392. Scene.prototype.getExternalData = function (key) {
  24393. if (!this._externalData) {
  24394. return null;
  24395. }
  24396. return this._externalData.get(key);
  24397. };
  24398. /**
  24399. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24400. * @param key the unique key that identifies the data
  24401. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24402. * @return the associated data, can be null if the factory returned null.
  24403. */
  24404. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24405. if (!this._externalData) {
  24406. this._externalData = new BABYLON.StringDictionary();
  24407. }
  24408. return this._externalData.getOrAddWithFactory(key, factory);
  24409. };
  24410. /**
  24411. * Remove an externaly attached data from the Engine instance
  24412. * @param key the unique key that identifies the data
  24413. * @return true if the data was successfully removed, false if it doesn't exist
  24414. */
  24415. Scene.prototype.removeExternalData = function (key) {
  24416. return this._externalData.remove(key);
  24417. };
  24418. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24419. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24420. if (mesh.showSubMeshesBoundingBox) {
  24421. var boundingInfo = subMesh.getBoundingInfo();
  24422. if (boundingInfo !== null && boundingInfo !== undefined) {
  24423. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24424. }
  24425. }
  24426. var material = subMesh.getMaterial();
  24427. if (material !== null && material !== undefined) {
  24428. // Render targets
  24429. if (material.getRenderTargetTextures !== undefined) {
  24430. if (this._processedMaterials.indexOf(material) === -1) {
  24431. this._processedMaterials.push(material);
  24432. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24433. }
  24434. }
  24435. // Dispatch
  24436. this._activeIndices.addCount(subMesh.indexCount, false);
  24437. this._renderingManager.dispatch(subMesh, mesh, material);
  24438. }
  24439. }
  24440. };
  24441. /**
  24442. * Clear the processed materials smart array preventing retention point in material dispose.
  24443. */
  24444. Scene.prototype.freeProcessedMaterials = function () {
  24445. this._processedMaterials.dispose();
  24446. };
  24447. /**
  24448. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24449. */
  24450. Scene.prototype.freeActiveMeshes = function () {
  24451. this._activeMeshes.dispose();
  24452. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24453. this.activeCamera._activeMeshes.dispose();
  24454. }
  24455. if (this.activeCameras) {
  24456. for (var i = 0; i < this.activeCameras.length; i++) {
  24457. var activeCamera = this.activeCameras[i];
  24458. if (activeCamera && activeCamera._activeMeshes) {
  24459. activeCamera._activeMeshes.dispose();
  24460. }
  24461. }
  24462. }
  24463. };
  24464. /**
  24465. * Clear the info related to rendering groups preventing retention points during dispose.
  24466. */
  24467. Scene.prototype.freeRenderingGroups = function () {
  24468. if (this._renderingManager) {
  24469. this._renderingManager.freeRenderingGroups();
  24470. }
  24471. if (this.textures) {
  24472. for (var i = 0; i < this.textures.length; i++) {
  24473. var texture = this.textures[i];
  24474. if (texture && texture.renderList) {
  24475. texture.freeRenderingGroups();
  24476. }
  24477. }
  24478. }
  24479. };
  24480. Scene.prototype._isInIntermediateRendering = function () {
  24481. return this._intermediateRendering;
  24482. };
  24483. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24484. this._activeMeshCandidateProvider = provider;
  24485. };
  24486. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24487. return this._activeMeshCandidateProvider;
  24488. };
  24489. /**
  24490. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24491. */
  24492. Scene.prototype.freezeActiveMeshes = function () {
  24493. if (!this.activeCamera) {
  24494. return this;
  24495. }
  24496. if (!this._frustumPlanes) {
  24497. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24498. }
  24499. this._evaluateActiveMeshes();
  24500. this._activeMeshesFrozen = true;
  24501. return this;
  24502. };
  24503. /**
  24504. * Use this function to restart evaluating active meshes on every frame
  24505. */
  24506. Scene.prototype.unfreezeActiveMeshes = function () {
  24507. this._activeMeshesFrozen = false;
  24508. return this;
  24509. };
  24510. Scene.prototype._evaluateActiveMeshes = function () {
  24511. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24512. return;
  24513. }
  24514. if (!this.activeCamera) {
  24515. return;
  24516. }
  24517. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24518. this.activeCamera._activeMeshes.reset();
  24519. this._activeMeshes.reset();
  24520. this._renderingManager.reset();
  24521. this._processedMaterials.reset();
  24522. this._activeParticleSystems.reset();
  24523. this._activeSkeletons.reset();
  24524. this._softwareSkinnedMeshes.reset();
  24525. if (this._boundingBoxRenderer) {
  24526. this._boundingBoxRenderer.reset();
  24527. }
  24528. // Meshes
  24529. var meshes;
  24530. var len;
  24531. var checkIsEnabled = true;
  24532. // Determine mesh candidates
  24533. if (this._activeMeshCandidateProvider !== undefined) {
  24534. // Use _activeMeshCandidateProvider
  24535. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24536. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24537. if (meshes !== undefined) {
  24538. len = meshes.length;
  24539. }
  24540. else {
  24541. len = 0;
  24542. }
  24543. }
  24544. else if (this._selectionOctree !== undefined) {
  24545. // Octree
  24546. var selection = this._selectionOctree.select(this._frustumPlanes);
  24547. meshes = selection.data;
  24548. len = selection.length;
  24549. }
  24550. else {
  24551. // Full scene traversal
  24552. len = this.meshes.length;
  24553. meshes = this.meshes;
  24554. }
  24555. // Check each mesh
  24556. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24557. mesh = meshes[meshIndex];
  24558. if (mesh.isBlocked) {
  24559. continue;
  24560. }
  24561. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24562. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24563. continue;
  24564. }
  24565. mesh.computeWorldMatrix();
  24566. // Intersections
  24567. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24568. this._meshesForIntersections.pushNoDuplicate(mesh);
  24569. }
  24570. // Switch to current LOD
  24571. meshLOD = mesh.getLOD(this.activeCamera);
  24572. if (meshLOD === undefined || meshLOD === null) {
  24573. continue;
  24574. }
  24575. mesh._preActivate();
  24576. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24577. this._activeMeshes.push(mesh);
  24578. this.activeCamera._activeMeshes.push(mesh);
  24579. mesh._activate(this._renderId);
  24580. if (meshLOD !== mesh) {
  24581. meshLOD._activate(this._renderId);
  24582. }
  24583. this._activeMesh(mesh, meshLOD);
  24584. }
  24585. }
  24586. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24587. // Particle systems
  24588. if (this.particlesEnabled) {
  24589. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24590. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24591. var particleSystem = this.particleSystems[particleIndex];
  24592. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24593. continue;
  24594. }
  24595. var emitter = particleSystem.emitter;
  24596. if (!emitter.position || emitter.isEnabled()) {
  24597. this._activeParticleSystems.push(particleSystem);
  24598. particleSystem.animate();
  24599. this._renderingManager.dispatchParticles(particleSystem);
  24600. }
  24601. }
  24602. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24603. }
  24604. };
  24605. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24606. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24607. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24608. mesh.skeleton.prepare();
  24609. }
  24610. if (!mesh.computeBonesUsingShaders) {
  24611. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24612. }
  24613. }
  24614. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24615. var boundingInfo = sourceMesh.getBoundingInfo();
  24616. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24617. }
  24618. if (mesh !== undefined && mesh !== null
  24619. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24620. // Submeshes Octrees
  24621. var len;
  24622. var subMeshes;
  24623. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24624. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24625. len = intersections.length;
  24626. subMeshes = intersections.data;
  24627. }
  24628. else {
  24629. subMeshes = mesh.subMeshes;
  24630. len = subMeshes.length;
  24631. }
  24632. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24633. subMesh = subMeshes[subIndex];
  24634. this._evaluateSubMesh(subMesh, mesh);
  24635. }
  24636. }
  24637. };
  24638. Scene.prototype.updateTransformMatrix = function (force) {
  24639. if (!this.activeCamera) {
  24640. return;
  24641. }
  24642. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24643. };
  24644. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24645. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24646. };
  24647. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24648. if (camera && camera._skipRendering) {
  24649. return;
  24650. }
  24651. var engine = this._engine;
  24652. this.activeCamera = camera;
  24653. if (!this.activeCamera)
  24654. throw new Error("Active camera not set");
  24655. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24656. // Viewport
  24657. engine.setViewport(this.activeCamera.viewport);
  24658. // Camera
  24659. this.resetCachedMaterial();
  24660. this._renderId++;
  24661. this.updateTransformMatrix();
  24662. if (camera._alternateCamera) {
  24663. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24664. this._alternateRendering = true;
  24665. }
  24666. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24667. // Meshes
  24668. this._evaluateActiveMeshes();
  24669. // Software skinning
  24670. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24671. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24672. mesh.applySkeleton(mesh.skeleton);
  24673. }
  24674. // Render targets
  24675. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24676. var needsRestoreFrameBuffer = false;
  24677. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24678. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24679. }
  24680. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24681. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24682. }
  24683. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24684. this._intermediateRendering = true;
  24685. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24686. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24687. var renderTarget = this._renderTargets.data[renderIndex];
  24688. if (renderTarget._shouldRender()) {
  24689. this._renderId++;
  24690. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24691. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24692. }
  24693. }
  24694. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24695. this._intermediateRendering = false;
  24696. this._renderId++;
  24697. needsRestoreFrameBuffer = true; // Restore back buffer
  24698. }
  24699. // Render EffecttLayer Texture
  24700. var stencilState = this._engine.getStencilBuffer();
  24701. var renderEffects = false;
  24702. var needStencil = false;
  24703. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24704. this._intermediateRendering = true;
  24705. for (var i = 0; i < this.effectLayers.length; i++) {
  24706. var effectLayer = this.effectLayers[i];
  24707. if (effectLayer.shouldRender() &&
  24708. (!effectLayer.camera ||
  24709. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24710. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24711. renderEffects = true;
  24712. needStencil = needStencil || effectLayer.needStencil();
  24713. var renderTarget = effectLayer._mainTexture;
  24714. if (renderTarget._shouldRender()) {
  24715. this._renderId++;
  24716. renderTarget.render(false, false);
  24717. needsRestoreFrameBuffer = true;
  24718. }
  24719. }
  24720. }
  24721. this._intermediateRendering = false;
  24722. this._renderId++;
  24723. }
  24724. if (needsRestoreFrameBuffer) {
  24725. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24726. }
  24727. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24728. // Prepare Frame
  24729. this.postProcessManager._prepareFrame();
  24730. // Backgrounds
  24731. var layerIndex;
  24732. var layer;
  24733. if (this.layers.length) {
  24734. engine.setDepthBuffer(false);
  24735. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24736. layer = this.layers[layerIndex];
  24737. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24738. layer.render();
  24739. }
  24740. }
  24741. engine.setDepthBuffer(true);
  24742. }
  24743. // Activate effect Layer stencil
  24744. if (needStencil) {
  24745. this._engine.setStencilBuffer(true);
  24746. }
  24747. // Render
  24748. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24749. this._renderingManager.render(null, null, true, true);
  24750. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24751. // Restore effect Layer stencil
  24752. if (needStencil) {
  24753. this._engine.setStencilBuffer(stencilState);
  24754. }
  24755. // Bounding boxes
  24756. if (this._boundingBoxRenderer) {
  24757. this._boundingBoxRenderer.render();
  24758. }
  24759. // Lens flares
  24760. if (this.lensFlaresEnabled) {
  24761. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24762. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24763. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24764. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24765. lensFlareSystem.render();
  24766. }
  24767. }
  24768. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24769. }
  24770. // Foregrounds
  24771. if (this.layers.length) {
  24772. engine.setDepthBuffer(false);
  24773. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24774. layer = this.layers[layerIndex];
  24775. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24776. layer.render();
  24777. }
  24778. }
  24779. engine.setDepthBuffer(true);
  24780. }
  24781. // Effect Layer
  24782. if (renderEffects) {
  24783. engine.setDepthBuffer(false);
  24784. for (var i = 0; i < this.effectLayers.length; i++) {
  24785. if (this.effectLayers[i].shouldRender()) {
  24786. this.effectLayers[i].render();
  24787. }
  24788. }
  24789. engine.setDepthBuffer(true);
  24790. }
  24791. // Finalize frame
  24792. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24793. // Reset some special arrays
  24794. this._renderTargets.reset();
  24795. this._alternateRendering = false;
  24796. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24797. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24798. };
  24799. Scene.prototype._processSubCameras = function (camera) {
  24800. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24801. this._renderForCamera(camera);
  24802. return;
  24803. }
  24804. // rig cameras
  24805. for (var index = 0; index < camera._rigCameras.length; index++) {
  24806. this._renderForCamera(camera._rigCameras[index], camera);
  24807. }
  24808. this.activeCamera = camera;
  24809. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24810. };
  24811. Scene.prototype._checkIntersections = function () {
  24812. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24813. var sourceMesh = this._meshesForIntersections.data[index];
  24814. if (!sourceMesh.actionManager) {
  24815. continue;
  24816. }
  24817. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24818. var action = sourceMesh.actionManager.actions[actionIndex];
  24819. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24820. var parameters = action.getTriggerParameter();
  24821. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24822. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24823. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24824. if (areIntersecting && currentIntersectionInProgress === -1) {
  24825. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24826. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24827. sourceMesh._intersectionsInProgress.push(otherMesh);
  24828. }
  24829. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24830. sourceMesh._intersectionsInProgress.push(otherMesh);
  24831. }
  24832. }
  24833. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24834. //They intersected, and now they don't.
  24835. //is this trigger an exit trigger? execute an event.
  24836. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24837. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24838. }
  24839. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24840. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24841. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24842. }
  24843. }
  24844. }
  24845. }
  24846. }
  24847. };
  24848. Scene.prototype.render = function () {
  24849. if (this.isDisposed) {
  24850. return;
  24851. }
  24852. this._activeParticles.fetchNewFrame();
  24853. this._totalVertices.fetchNewFrame();
  24854. this._activeIndices.fetchNewFrame();
  24855. this._activeBones.fetchNewFrame();
  24856. this._meshesForIntersections.reset();
  24857. this.resetCachedMaterial();
  24858. this.onBeforeAnimationsObservable.notifyObservers(this);
  24859. // Actions
  24860. if (this.actionManager) {
  24861. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24862. }
  24863. //Simplification Queue
  24864. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24865. this.simplificationQueue.executeNext();
  24866. }
  24867. if (this._engine.isDeterministicLockStep()) {
  24868. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24869. var defaultFPS = (60.0 / 1000.0);
  24870. var defaultFrameTime = 1000 / 60; // frame time in MS
  24871. if (this._physicsEngine) {
  24872. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24873. }
  24874. var stepsTaken = 0;
  24875. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24876. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24877. internalSteps = Math.min(internalSteps, maxSubSteps);
  24878. do {
  24879. this.onBeforeStepObservable.notifyObservers(this);
  24880. // Animations
  24881. this._animationRatio = defaultFrameTime * defaultFPS;
  24882. this._animate();
  24883. this.onAfterAnimationsObservable.notifyObservers(this);
  24884. // Physics
  24885. if (this._physicsEngine) {
  24886. this.onBeforePhysicsObservable.notifyObservers(this);
  24887. this._physicsEngine._step(defaultFrameTime / 1000);
  24888. this.onAfterPhysicsObservable.notifyObservers(this);
  24889. }
  24890. this.onAfterStepObservable.notifyObservers(this);
  24891. this._currentStepId++;
  24892. stepsTaken++;
  24893. deltaTime -= defaultFrameTime;
  24894. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24895. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24896. }
  24897. else {
  24898. // Animations
  24899. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24900. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24901. this._animate();
  24902. this.onAfterAnimationsObservable.notifyObservers(this);
  24903. // Physics
  24904. if (this._physicsEngine) {
  24905. this.onBeforePhysicsObservable.notifyObservers(this);
  24906. this._physicsEngine._step(deltaTime / 1000.0);
  24907. this.onAfterPhysicsObservable.notifyObservers(this);
  24908. }
  24909. }
  24910. // update gamepad manager
  24911. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24912. this._gamepadManager._checkGamepadsStatus();
  24913. }
  24914. // Update Cameras
  24915. if (this.activeCameras.length > 0) {
  24916. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24917. var camera = this.activeCameras[cameraIndex];
  24918. camera.update();
  24919. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24920. // rig cameras
  24921. for (var index = 0; index < camera._rigCameras.length; index++) {
  24922. camera._rigCameras[index].update();
  24923. }
  24924. }
  24925. }
  24926. }
  24927. else if (this.activeCamera) {
  24928. this.activeCamera.update();
  24929. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24930. // rig cameras
  24931. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24932. this.activeCamera._rigCameras[index].update();
  24933. }
  24934. }
  24935. }
  24936. // Before render
  24937. this.onBeforeRenderObservable.notifyObservers(this);
  24938. // Customs render targets
  24939. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24940. var engine = this.getEngine();
  24941. var currentActiveCamera = this.activeCamera;
  24942. if (this.renderTargetsEnabled) {
  24943. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24944. this._intermediateRendering = true;
  24945. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24946. var renderTarget = this.customRenderTargets[customIndex];
  24947. if (renderTarget._shouldRender()) {
  24948. this._renderId++;
  24949. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24950. if (!this.activeCamera)
  24951. throw new Error("Active camera not set");
  24952. // Viewport
  24953. engine.setViewport(this.activeCamera.viewport);
  24954. // Camera
  24955. this.updateTransformMatrix();
  24956. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24957. }
  24958. }
  24959. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24960. this._intermediateRendering = false;
  24961. this._renderId++;
  24962. }
  24963. // Restore back buffer
  24964. if (this.customRenderTargets.length > 0) {
  24965. engine.restoreDefaultFramebuffer();
  24966. }
  24967. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24968. this.activeCamera = currentActiveCamera;
  24969. // Procedural textures
  24970. if (this.proceduralTexturesEnabled) {
  24971. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24972. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24973. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24974. if (proceduralTexture._shouldRender()) {
  24975. proceduralTexture.render();
  24976. }
  24977. }
  24978. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24979. }
  24980. // Clear
  24981. if (this.autoClearDepthAndStencil || this.autoClear) {
  24982. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24983. }
  24984. // Shadows
  24985. if (this.shadowsEnabled) {
  24986. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24987. var light = this.lights[lightIndex];
  24988. var shadowGenerator = light.getShadowGenerator();
  24989. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24990. var shadowMap = (shadowGenerator.getShadowMap());
  24991. if (this.textures.indexOf(shadowMap) !== -1) {
  24992. this._renderTargets.push(shadowMap);
  24993. }
  24994. }
  24995. }
  24996. }
  24997. // Depth renderer
  24998. for (var key in this._depthRenderer) {
  24999. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  25000. }
  25001. // Geometry renderer
  25002. if (this._geometryBufferRenderer) {
  25003. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  25004. }
  25005. // RenderPipeline
  25006. if (this._postProcessRenderPipelineManager) {
  25007. this._postProcessRenderPipelineManager.update();
  25008. }
  25009. // Multi-cameras?
  25010. if (this.activeCameras.length > 0) {
  25011. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  25012. if (cameraIndex > 0) {
  25013. this._engine.clear(null, false, true, true);
  25014. }
  25015. this._processSubCameras(this.activeCameras[cameraIndex]);
  25016. }
  25017. }
  25018. else {
  25019. if (!this.activeCamera) {
  25020. throw new Error("No camera defined");
  25021. }
  25022. this._processSubCameras(this.activeCamera);
  25023. }
  25024. // Intersection checks
  25025. this._checkIntersections();
  25026. // Update the audio listener attached to the camera
  25027. if (BABYLON.AudioEngine) {
  25028. this._updateAudioParameters();
  25029. }
  25030. // After render
  25031. if (this.afterRender) {
  25032. this.afterRender();
  25033. }
  25034. this.onAfterRenderObservable.notifyObservers(this);
  25035. // Cleaning
  25036. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25037. var data = this._toBeDisposed.data[index];
  25038. if (data) {
  25039. data.dispose();
  25040. }
  25041. this._toBeDisposed[index] = null;
  25042. }
  25043. this._toBeDisposed.reset();
  25044. if (this.dumpNextRenderTargets) {
  25045. this.dumpNextRenderTargets = false;
  25046. }
  25047. this._activeBones.addCount(0, true);
  25048. this._activeIndices.addCount(0, true);
  25049. this._activeParticles.addCount(0, true);
  25050. };
  25051. Scene.prototype._updateAudioParameters = function () {
  25052. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25053. return;
  25054. }
  25055. var listeningCamera;
  25056. var audioEngine = BABYLON.Engine.audioEngine;
  25057. if (this.activeCameras.length > 0) {
  25058. listeningCamera = this.activeCameras[0];
  25059. }
  25060. else {
  25061. listeningCamera = this.activeCamera;
  25062. }
  25063. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25064. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25065. // for VR cameras
  25066. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25067. listeningCamera = listeningCamera.rigCameras[0];
  25068. }
  25069. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25070. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25071. cameraDirection.normalize();
  25072. // To avoid some errors on GearVR
  25073. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25074. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25075. }
  25076. var i;
  25077. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25078. var sound = this.mainSoundTrack.soundCollection[i];
  25079. if (sound.useCustomAttenuation) {
  25080. sound.updateDistanceFromListener();
  25081. }
  25082. }
  25083. for (i = 0; i < this.soundTracks.length; i++) {
  25084. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25085. sound = this.soundTracks[i].soundCollection[j];
  25086. if (sound.useCustomAttenuation) {
  25087. sound.updateDistanceFromListener();
  25088. }
  25089. }
  25090. }
  25091. }
  25092. };
  25093. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25094. // Audio
  25095. get: function () {
  25096. return this._audioEnabled;
  25097. },
  25098. set: function (value) {
  25099. this._audioEnabled = value;
  25100. if (BABYLON.AudioEngine) {
  25101. if (this._audioEnabled) {
  25102. this._enableAudio();
  25103. }
  25104. else {
  25105. this._disableAudio();
  25106. }
  25107. }
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. Scene.prototype._disableAudio = function () {
  25113. var i;
  25114. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25115. this.mainSoundTrack.soundCollection[i].pause();
  25116. }
  25117. for (i = 0; i < this.soundTracks.length; i++) {
  25118. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25119. this.soundTracks[i].soundCollection[j].pause();
  25120. }
  25121. }
  25122. };
  25123. Scene.prototype._enableAudio = function () {
  25124. var i;
  25125. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25126. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25127. this.mainSoundTrack.soundCollection[i].play();
  25128. }
  25129. }
  25130. for (i = 0; i < this.soundTracks.length; i++) {
  25131. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25132. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25133. this.soundTracks[i].soundCollection[j].play();
  25134. }
  25135. }
  25136. }
  25137. };
  25138. Object.defineProperty(Scene.prototype, "headphone", {
  25139. get: function () {
  25140. return this._headphone;
  25141. },
  25142. set: function (value) {
  25143. this._headphone = value;
  25144. if (BABYLON.AudioEngine) {
  25145. if (this._headphone) {
  25146. this._switchAudioModeForHeadphones();
  25147. }
  25148. else {
  25149. this._switchAudioModeForNormalSpeakers();
  25150. }
  25151. }
  25152. },
  25153. enumerable: true,
  25154. configurable: true
  25155. });
  25156. Scene.prototype._switchAudioModeForHeadphones = function () {
  25157. this.mainSoundTrack.switchPanningModelToHRTF();
  25158. for (var i = 0; i < this.soundTracks.length; i++) {
  25159. this.soundTracks[i].switchPanningModelToHRTF();
  25160. }
  25161. };
  25162. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25163. this.mainSoundTrack.switchPanningModelToEqualPower();
  25164. for (var i = 0; i < this.soundTracks.length; i++) {
  25165. this.soundTracks[i].switchPanningModelToEqualPower();
  25166. }
  25167. };
  25168. /**
  25169. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25170. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25171. * @returns the created depth renderer
  25172. */
  25173. Scene.prototype.enableDepthRenderer = function (camera) {
  25174. camera = camera || this.activeCamera;
  25175. if (!camera) {
  25176. throw "No camera available to enable depth renderer";
  25177. }
  25178. if (!this._depthRenderer[camera.id]) {
  25179. var textureType = 0;
  25180. if (this._engine.getCaps().textureHalfFloatRender) {
  25181. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25182. }
  25183. else if (this._engine.getCaps().textureFloatRender) {
  25184. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25185. }
  25186. else {
  25187. throw "Depth renderer does not support int texture type";
  25188. }
  25189. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25190. }
  25191. return this._depthRenderer[camera.id];
  25192. };
  25193. /**
  25194. * Disables a depth renderer for a given camera
  25195. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25196. */
  25197. Scene.prototype.disableDepthRenderer = function (camera) {
  25198. camera = camera || this.activeCamera;
  25199. if (!camera || !this._depthRenderer[camera.id]) {
  25200. return;
  25201. }
  25202. this._depthRenderer[camera.id].dispose();
  25203. delete this._depthRenderer[camera.id];
  25204. };
  25205. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25206. if (ratio === void 0) { ratio = 1; }
  25207. if (this._geometryBufferRenderer) {
  25208. return this._geometryBufferRenderer;
  25209. }
  25210. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25211. if (!this._geometryBufferRenderer.isSupported) {
  25212. this._geometryBufferRenderer = null;
  25213. }
  25214. return this._geometryBufferRenderer;
  25215. };
  25216. Scene.prototype.disableGeometryBufferRenderer = function () {
  25217. if (!this._geometryBufferRenderer) {
  25218. return;
  25219. }
  25220. this._geometryBufferRenderer.dispose();
  25221. this._geometryBufferRenderer = null;
  25222. };
  25223. Scene.prototype.freezeMaterials = function () {
  25224. for (var i = 0; i < this.materials.length; i++) {
  25225. this.materials[i].freeze();
  25226. }
  25227. };
  25228. Scene.prototype.unfreezeMaterials = function () {
  25229. for (var i = 0; i < this.materials.length; i++) {
  25230. this.materials[i].unfreeze();
  25231. }
  25232. };
  25233. Scene.prototype.dispose = function () {
  25234. this.beforeRender = null;
  25235. this.afterRender = null;
  25236. this.skeletons = [];
  25237. this.morphTargetManagers = [];
  25238. this.importedMeshesFiles = new Array();
  25239. this.stopAllAnimations();
  25240. this.resetCachedMaterial();
  25241. for (var key in this._depthRenderer) {
  25242. this._depthRenderer[key].dispose();
  25243. }
  25244. if (this._gamepadManager) {
  25245. this._gamepadManager.dispose();
  25246. this._gamepadManager = null;
  25247. }
  25248. // Smart arrays
  25249. if (this.activeCamera) {
  25250. this.activeCamera._activeMeshes.dispose();
  25251. this.activeCamera = null;
  25252. }
  25253. this._activeMeshes.dispose();
  25254. this._renderingManager.dispose();
  25255. this._processedMaterials.dispose();
  25256. this._activeParticleSystems.dispose();
  25257. this._activeSkeletons.dispose();
  25258. this._softwareSkinnedMeshes.dispose();
  25259. this._renderTargets.dispose();
  25260. this._registeredForLateAnimationBindings.dispose();
  25261. if (this._boundingBoxRenderer) {
  25262. this._boundingBoxRenderer.dispose();
  25263. }
  25264. this._meshesForIntersections.dispose();
  25265. this._toBeDisposed.dispose();
  25266. // Abort active requests
  25267. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25268. var request = _a[_i];
  25269. request.abort();
  25270. }
  25271. // Debug layer
  25272. if (this._debugLayer) {
  25273. this._debugLayer.hide();
  25274. }
  25275. // Events
  25276. this.onDisposeObservable.notifyObservers(this);
  25277. this.onDisposeObservable.clear();
  25278. this.onBeforeRenderObservable.clear();
  25279. this.onAfterRenderObservable.clear();
  25280. this.OnBeforeRenderTargetsRenderObservable.clear();
  25281. this.OnAfterRenderTargetsRenderObservable.clear();
  25282. this.onAfterStepObservable.clear();
  25283. this.onBeforeStepObservable.clear();
  25284. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25285. this.onAfterActiveMeshesEvaluationObservable.clear();
  25286. this.onBeforeParticlesRenderingObservable.clear();
  25287. this.onAfterParticlesRenderingObservable.clear();
  25288. this.onBeforeSpritesRenderingObservable.clear();
  25289. this.onAfterSpritesRenderingObservable.clear();
  25290. this.onBeforeDrawPhaseObservable.clear();
  25291. this.onAfterDrawPhaseObservable.clear();
  25292. this.onBeforePhysicsObservable.clear();
  25293. this.onAfterPhysicsObservable.clear();
  25294. this.onBeforeAnimationsObservable.clear();
  25295. this.onAfterAnimationsObservable.clear();
  25296. this.onDataLoadedObservable.clear();
  25297. this.detachControl();
  25298. // Release sounds & sounds tracks
  25299. if (BABYLON.AudioEngine) {
  25300. this.disposeSounds();
  25301. }
  25302. // VR Helper
  25303. if (this.VRHelper) {
  25304. this.VRHelper.dispose();
  25305. }
  25306. // Detach cameras
  25307. var canvas = this._engine.getRenderingCanvas();
  25308. if (canvas) {
  25309. var index;
  25310. for (index = 0; index < this.cameras.length; index++) {
  25311. this.cameras[index].detachControl(canvas);
  25312. }
  25313. }
  25314. // Release animation groups
  25315. while (this.animationGroups.length) {
  25316. this.animationGroups[0].dispose();
  25317. }
  25318. // Release lights
  25319. while (this.lights.length) {
  25320. this.lights[0].dispose();
  25321. }
  25322. // Release meshes
  25323. while (this.meshes.length) {
  25324. this.meshes[0].dispose(true);
  25325. }
  25326. while (this.transformNodes.length) {
  25327. this.removeTransformNode(this.transformNodes[0]);
  25328. }
  25329. // Release cameras
  25330. while (this.cameras.length) {
  25331. this.cameras[0].dispose();
  25332. }
  25333. // Release materials
  25334. if (this.defaultMaterial) {
  25335. this.defaultMaterial.dispose();
  25336. }
  25337. while (this.multiMaterials.length) {
  25338. this.multiMaterials[0].dispose();
  25339. }
  25340. while (this.materials.length) {
  25341. this.materials[0].dispose();
  25342. }
  25343. // Release particles
  25344. while (this.particleSystems.length) {
  25345. this.particleSystems[0].dispose();
  25346. }
  25347. // Release sprites
  25348. while (this.spriteManagers.length) {
  25349. this.spriteManagers[0].dispose();
  25350. }
  25351. // Release postProcesses
  25352. while (this.postProcesses.length) {
  25353. this.postProcesses[0].dispose();
  25354. }
  25355. // Release layers
  25356. while (this.layers.length) {
  25357. this.layers[0].dispose();
  25358. }
  25359. while (this.effectLayers.length) {
  25360. this.effectLayers[0].dispose();
  25361. }
  25362. // Release textures
  25363. while (this.textures.length) {
  25364. this.textures[0].dispose();
  25365. }
  25366. // Release UBO
  25367. this._sceneUbo.dispose();
  25368. if (this._alternateSceneUbo) {
  25369. this._alternateSceneUbo.dispose();
  25370. }
  25371. // Post-processes
  25372. this.postProcessManager.dispose();
  25373. if (this._postProcessRenderPipelineManager) {
  25374. this._postProcessRenderPipelineManager.dispose();
  25375. }
  25376. // Physics
  25377. if (this._physicsEngine) {
  25378. this.disablePhysicsEngine();
  25379. }
  25380. // Remove from engine
  25381. index = this._engine.scenes.indexOf(this);
  25382. if (index > -1) {
  25383. this._engine.scenes.splice(index, 1);
  25384. }
  25385. this._engine.wipeCaches(true);
  25386. this._isDisposed = true;
  25387. };
  25388. Object.defineProperty(Scene.prototype, "isDisposed", {
  25389. get: function () {
  25390. return this._isDisposed;
  25391. },
  25392. enumerable: true,
  25393. configurable: true
  25394. });
  25395. // Release sounds & sounds tracks
  25396. Scene.prototype.disposeSounds = function () {
  25397. if (!this._mainSoundTrack) {
  25398. return;
  25399. }
  25400. this.mainSoundTrack.dispose();
  25401. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25402. this.soundTracks[scIndex].dispose();
  25403. }
  25404. };
  25405. // Octrees
  25406. /**
  25407. * Get the world extend vectors with an optional filter
  25408. *
  25409. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25410. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25411. */
  25412. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25413. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25414. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25415. filterPredicate = filterPredicate || (function () { return true; });
  25416. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25417. mesh.computeWorldMatrix(true);
  25418. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25419. return;
  25420. }
  25421. var boundingInfo = mesh.getBoundingInfo();
  25422. var minBox = boundingInfo.boundingBox.minimumWorld;
  25423. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25424. BABYLON.Tools.CheckExtends(minBox, min, max);
  25425. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25426. });
  25427. return {
  25428. min: min,
  25429. max: max
  25430. };
  25431. };
  25432. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25433. if (maxCapacity === void 0) { maxCapacity = 64; }
  25434. if (maxDepth === void 0) { maxDepth = 2; }
  25435. if (!this._selectionOctree) {
  25436. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25437. }
  25438. var worldExtends = this.getWorldExtends();
  25439. // Update octree
  25440. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25441. return this._selectionOctree;
  25442. };
  25443. // Picking
  25444. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25445. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25446. var result = BABYLON.Ray.Zero();
  25447. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25448. return result;
  25449. };
  25450. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25451. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25452. var engine = this._engine;
  25453. if (!camera) {
  25454. if (!this.activeCamera)
  25455. throw new Error("Active camera not set");
  25456. camera = this.activeCamera;
  25457. }
  25458. var cameraViewport = camera.viewport;
  25459. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25460. // Moving coordinates to local viewport world
  25461. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25462. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25463. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25464. return this;
  25465. };
  25466. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25467. var result = BABYLON.Ray.Zero();
  25468. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25469. return result;
  25470. };
  25471. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25472. if (!BABYLON.PickingInfo) {
  25473. return this;
  25474. }
  25475. var engine = this._engine;
  25476. if (!camera) {
  25477. if (!this.activeCamera)
  25478. throw new Error("Active camera not set");
  25479. camera = this.activeCamera;
  25480. }
  25481. var cameraViewport = camera.viewport;
  25482. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25483. var identity = BABYLON.Matrix.Identity();
  25484. // Moving coordinates to local viewport world
  25485. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25486. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25487. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25488. return this;
  25489. };
  25490. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25491. if (!BABYLON.PickingInfo) {
  25492. return null;
  25493. }
  25494. var pickingInfo = null;
  25495. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25496. var mesh = this.meshes[meshIndex];
  25497. if (predicate) {
  25498. if (!predicate(mesh)) {
  25499. continue;
  25500. }
  25501. }
  25502. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25503. continue;
  25504. }
  25505. var world = mesh.getWorldMatrix();
  25506. var ray = rayFunction(world);
  25507. var result = mesh.intersects(ray, fastCheck);
  25508. if (!result || !result.hit)
  25509. continue;
  25510. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25511. continue;
  25512. pickingInfo = result;
  25513. if (fastCheck) {
  25514. break;
  25515. }
  25516. }
  25517. return pickingInfo || new BABYLON.PickingInfo();
  25518. };
  25519. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25520. if (!BABYLON.PickingInfo) {
  25521. return null;
  25522. }
  25523. var pickingInfos = new Array();
  25524. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25525. var mesh = this.meshes[meshIndex];
  25526. if (predicate) {
  25527. if (!predicate(mesh)) {
  25528. continue;
  25529. }
  25530. }
  25531. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25532. continue;
  25533. }
  25534. var world = mesh.getWorldMatrix();
  25535. var ray = rayFunction(world);
  25536. var result = mesh.intersects(ray, false);
  25537. if (!result || !result.hit)
  25538. continue;
  25539. pickingInfos.push(result);
  25540. }
  25541. return pickingInfos;
  25542. };
  25543. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25544. if (!BABYLON.PickingInfo) {
  25545. return null;
  25546. }
  25547. var pickingInfo = null;
  25548. if (!camera) {
  25549. if (!this.activeCamera) {
  25550. return null;
  25551. }
  25552. camera = this.activeCamera;
  25553. }
  25554. if (this.spriteManagers.length > 0) {
  25555. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25556. var spriteManager = this.spriteManagers[spriteIndex];
  25557. if (!spriteManager.isPickable) {
  25558. continue;
  25559. }
  25560. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25561. if (!result || !result.hit)
  25562. continue;
  25563. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25564. continue;
  25565. pickingInfo = result;
  25566. if (fastCheck) {
  25567. break;
  25568. }
  25569. }
  25570. }
  25571. return pickingInfo || new BABYLON.PickingInfo();
  25572. };
  25573. /** Launch a ray to try to pick a mesh in the scene
  25574. * @param x position on screen
  25575. * @param y position on screen
  25576. * @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
  25577. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25578. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25579. */
  25580. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25581. var _this = this;
  25582. if (!BABYLON.PickingInfo) {
  25583. return null;
  25584. }
  25585. return this._internalPick(function (world) {
  25586. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25587. return _this._tempPickingRay;
  25588. }, predicate, fastCheck);
  25589. };
  25590. /** Launch a ray to try to pick a sprite in the scene
  25591. * @param x position on screen
  25592. * @param y position on screen
  25593. * @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
  25594. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25595. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25596. */
  25597. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25598. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25599. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25600. };
  25601. /** Use the given ray to pick a mesh in the scene
  25602. * @param ray The ray to use to pick meshes
  25603. * @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
  25604. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25605. */
  25606. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25607. var _this = this;
  25608. return this._internalPick(function (world) {
  25609. if (!_this._pickWithRayInverseMatrix) {
  25610. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25611. }
  25612. world.invertToRef(_this._pickWithRayInverseMatrix);
  25613. if (!_this._cachedRayForTransform) {
  25614. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25615. }
  25616. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25617. return _this._cachedRayForTransform;
  25618. }, predicate, fastCheck);
  25619. };
  25620. /**
  25621. * Launch a ray to try to pick a mesh in the scene
  25622. * @param x X position on screen
  25623. * @param y Y position on screen
  25624. * @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
  25625. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25626. */
  25627. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25628. var _this = this;
  25629. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25630. };
  25631. /**
  25632. * Launch a ray to try to pick a mesh in the scene
  25633. * @param ray Ray to use
  25634. * @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
  25635. */
  25636. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25637. var _this = this;
  25638. return this._internalMultiPick(function (world) {
  25639. if (!_this._pickWithRayInverseMatrix) {
  25640. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25641. }
  25642. world.invertToRef(_this._pickWithRayInverseMatrix);
  25643. if (!_this._cachedRayForTransform) {
  25644. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25645. }
  25646. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25647. return _this._cachedRayForTransform;
  25648. }, predicate);
  25649. };
  25650. Scene.prototype.setPointerOverMesh = function (mesh) {
  25651. if (this._pointerOverMesh === mesh) {
  25652. return;
  25653. }
  25654. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25655. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25656. }
  25657. this._pointerOverMesh = mesh;
  25658. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25659. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25660. }
  25661. };
  25662. Scene.prototype.getPointerOverMesh = function () {
  25663. return this._pointerOverMesh;
  25664. };
  25665. Scene.prototype.setPointerOverSprite = function (sprite) {
  25666. if (this._pointerOverSprite === sprite) {
  25667. return;
  25668. }
  25669. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25670. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25671. }
  25672. this._pointerOverSprite = sprite;
  25673. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25674. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25675. }
  25676. };
  25677. Scene.prototype.getPointerOverSprite = function () {
  25678. return this._pointerOverSprite;
  25679. };
  25680. // Physics
  25681. Scene.prototype.getPhysicsEngine = function () {
  25682. return this._physicsEngine;
  25683. };
  25684. /**
  25685. * Enables physics to the current scene
  25686. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25687. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25688. * @return {boolean} was the physics engine initialized
  25689. */
  25690. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25691. if (gravity === void 0) { gravity = null; }
  25692. if (this._physicsEngine) {
  25693. return true;
  25694. }
  25695. try {
  25696. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25697. return true;
  25698. }
  25699. catch (e) {
  25700. BABYLON.Tools.Error(e.message);
  25701. return false;
  25702. }
  25703. };
  25704. Scene.prototype.disablePhysicsEngine = function () {
  25705. if (!this._physicsEngine) {
  25706. return;
  25707. }
  25708. this._physicsEngine.dispose();
  25709. this._physicsEngine = null;
  25710. };
  25711. Scene.prototype.isPhysicsEnabled = function () {
  25712. return this._physicsEngine !== undefined;
  25713. };
  25714. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25715. var mesh = compound.parts[0].mesh;
  25716. if (mesh.physicsImpostor) {
  25717. mesh.physicsImpostor.dispose();
  25718. mesh.physicsImpostor = null;
  25719. }
  25720. };
  25721. // Misc.
  25722. Scene.prototype._rebuildGeometries = function () {
  25723. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25724. var geometry = _a[_i];
  25725. geometry._rebuild();
  25726. }
  25727. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25728. var mesh = _c[_b];
  25729. mesh._rebuild();
  25730. }
  25731. if (this.postProcessManager) {
  25732. this.postProcessManager._rebuild();
  25733. }
  25734. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25735. var layer = _e[_d];
  25736. layer._rebuild();
  25737. }
  25738. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25739. var effectLayer = _g[_f];
  25740. effectLayer._rebuild();
  25741. }
  25742. if (this._boundingBoxRenderer) {
  25743. this._boundingBoxRenderer._rebuild();
  25744. }
  25745. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25746. var system = _j[_h];
  25747. system.rebuild();
  25748. }
  25749. if (this._postProcessRenderPipelineManager) {
  25750. this._postProcessRenderPipelineManager._rebuild();
  25751. }
  25752. };
  25753. Scene.prototype._rebuildTextures = function () {
  25754. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25755. var texture = _a[_i];
  25756. texture._rebuild();
  25757. }
  25758. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25759. };
  25760. /**
  25761. * Creates a default light for the scene.
  25762. * @param replace Whether to replace the existing lights in the scene.
  25763. */
  25764. Scene.prototype.createDefaultLight = function (replace) {
  25765. if (replace === void 0) { replace = false; }
  25766. // Dispose existing light in replace mode.
  25767. if (replace) {
  25768. if (this.lights) {
  25769. for (var i = 0; i < this.lights.length; i++) {
  25770. this.lights[i].dispose();
  25771. }
  25772. }
  25773. }
  25774. // Light
  25775. if (this.lights.length === 0) {
  25776. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25777. }
  25778. };
  25779. /**
  25780. * Creates a default camera for the scene.
  25781. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25782. * @param replace Whether to replace the existing active camera in the scene.
  25783. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25784. */
  25785. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25786. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25787. if (replace === void 0) { replace = false; }
  25788. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25789. // Dispose existing camera in replace mode.
  25790. if (replace) {
  25791. if (this.activeCamera) {
  25792. this.activeCamera.dispose();
  25793. this.activeCamera = null;
  25794. }
  25795. }
  25796. // Camera
  25797. if (!this.activeCamera) {
  25798. var worldExtends = this.getWorldExtends();
  25799. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25800. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25801. var camera;
  25802. var radius = worldSize.length() * 1.5;
  25803. // empty scene scenario!
  25804. if (!isFinite(radius)) {
  25805. radius = 1;
  25806. worldCenter.copyFromFloats(0, 0, 0);
  25807. }
  25808. if (createArcRotateCamera) {
  25809. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25810. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25811. arcRotateCamera.wheelPrecision = 100 / radius;
  25812. camera = arcRotateCamera;
  25813. }
  25814. else {
  25815. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25816. freeCamera.setTarget(worldCenter);
  25817. camera = freeCamera;
  25818. }
  25819. camera.minZ = radius * 0.01;
  25820. camera.maxZ = radius * 1000;
  25821. camera.speed = radius * 0.2;
  25822. this.activeCamera = camera;
  25823. var canvas = this.getEngine().getRenderingCanvas();
  25824. if (attachCameraControls && canvas) {
  25825. camera.attachControl(canvas);
  25826. }
  25827. }
  25828. };
  25829. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25830. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25831. if (replace === void 0) { replace = false; }
  25832. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25833. this.createDefaultLight(replace);
  25834. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25835. };
  25836. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25837. if (pbr === void 0) { pbr = false; }
  25838. if (scale === void 0) { scale = 1000; }
  25839. if (blur === void 0) { blur = 0; }
  25840. if (environmentTexture) {
  25841. this.environmentTexture = environmentTexture;
  25842. }
  25843. if (!this.environmentTexture) {
  25844. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25845. return null;
  25846. }
  25847. // Skybox
  25848. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25849. if (pbr) {
  25850. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25851. hdrSkyboxMaterial.backFaceCulling = false;
  25852. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25853. if (hdrSkyboxMaterial.reflectionTexture) {
  25854. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25855. }
  25856. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25857. hdrSkyboxMaterial.disableLighting = true;
  25858. hdrSkyboxMaterial.twoSidedLighting = true;
  25859. hdrSkybox.infiniteDistance = true;
  25860. hdrSkybox.material = hdrSkyboxMaterial;
  25861. }
  25862. else {
  25863. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25864. skyboxMaterial.backFaceCulling = false;
  25865. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25866. if (skyboxMaterial.reflectionTexture) {
  25867. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25868. }
  25869. skyboxMaterial.disableLighting = true;
  25870. hdrSkybox.infiniteDistance = true;
  25871. hdrSkybox.material = skyboxMaterial;
  25872. }
  25873. return hdrSkybox;
  25874. };
  25875. Scene.prototype.createDefaultEnvironment = function (options) {
  25876. if (BABYLON.EnvironmentHelper) {
  25877. return new BABYLON.EnvironmentHelper(options, this);
  25878. }
  25879. return null;
  25880. };
  25881. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25882. if (webVROptions === void 0) { webVROptions = {}; }
  25883. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25884. };
  25885. // Tags
  25886. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25887. if (tagsQuery === undefined) {
  25888. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25889. return list;
  25890. }
  25891. var listByTags = [];
  25892. forEach = forEach || (function (item) { return; });
  25893. for (var i in list) {
  25894. var item = list[i];
  25895. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25896. listByTags.push(item);
  25897. forEach(item);
  25898. }
  25899. }
  25900. return listByTags;
  25901. };
  25902. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25903. return this._getByTags(this.meshes, tagsQuery, forEach);
  25904. };
  25905. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25906. return this._getByTags(this.cameras, tagsQuery, forEach);
  25907. };
  25908. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25909. return this._getByTags(this.lights, tagsQuery, forEach);
  25910. };
  25911. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25912. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25913. };
  25914. /**
  25915. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25916. * This allowed control for front to back rendering or reversly depending of the special needs.
  25917. *
  25918. * @param renderingGroupId The rendering group id corresponding to its index
  25919. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25920. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25921. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25922. */
  25923. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25924. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25925. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25926. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25927. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25928. };
  25929. /**
  25930. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25931. *
  25932. * @param renderingGroupId The rendering group id corresponding to its index
  25933. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25934. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25935. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25936. */
  25937. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25938. if (depth === void 0) { depth = true; }
  25939. if (stencil === void 0) { stencil = true; }
  25940. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25941. };
  25942. /**
  25943. * Will flag all materials as dirty to trigger new shader compilation
  25944. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25945. */
  25946. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25947. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25948. var material = _a[_i];
  25949. if (predicate && !predicate(material)) {
  25950. continue;
  25951. }
  25952. material.markAsDirty(flag);
  25953. }
  25954. };
  25955. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25956. var _this = this;
  25957. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25958. this._activeRequests.push(request);
  25959. request.onCompleteObservable.add(function (request) {
  25960. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25961. });
  25962. return request;
  25963. };
  25964. /** @ignore */
  25965. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25966. var _this = this;
  25967. return new Promise(function (resolve, reject) {
  25968. _this._loadFile(url, function (data) {
  25969. resolve(data);
  25970. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25971. reject(exception);
  25972. });
  25973. });
  25974. };
  25975. // Statics
  25976. Scene._FOGMODE_NONE = 0;
  25977. Scene._FOGMODE_EXP = 1;
  25978. Scene._FOGMODE_EXP2 = 2;
  25979. Scene._FOGMODE_LINEAR = 3;
  25980. Scene._uniqueIdCounter = 0;
  25981. Scene.MinDeltaTime = 1.0;
  25982. Scene.MaxDeltaTime = 1000.0;
  25983. /** The distance in pixel that you have to move to prevent some events */
  25984. Scene.DragMovementThreshold = 10; // in pixels
  25985. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25986. Scene.LongPressDelay = 500; // in milliseconds
  25987. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25988. Scene.DoubleClickDelay = 300; // in milliseconds
  25989. /** If you need to check double click without raising a single click at first click, enable this flag */
  25990. Scene.ExclusiveDoubleClickMode = false;
  25991. return Scene;
  25992. }());
  25993. BABYLON.Scene = Scene;
  25994. })(BABYLON || (BABYLON = {}));
  25995. //# sourceMappingURL=babylon.scene.js.map
  25996. "use strict";
  25997. var BABYLON;
  25998. (function (BABYLON) {
  25999. /**
  26000. * Set of assets to keep when moving a scene into an asset container.
  26001. */
  26002. var KeepAssets = /** @class */ (function () {
  26003. function KeepAssets() {
  26004. /**
  26005. * Cameras to keep.
  26006. */
  26007. this.cameras = new Array();
  26008. /**
  26009. * Lights to keep.
  26010. */
  26011. this.lights = new Array();
  26012. /**
  26013. * Meshes to keep.
  26014. */
  26015. this.meshes = new Array();
  26016. /**
  26017. * Skeletons to keep.
  26018. */
  26019. this.skeletons = new Array();
  26020. /**
  26021. * ParticleSystems to keep.
  26022. */
  26023. this.particleSystems = new Array();
  26024. /**
  26025. * Animations to keep.
  26026. */
  26027. this.animations = new Array();
  26028. /**
  26029. * MultiMaterials to keep.
  26030. */
  26031. this.multiMaterials = new Array();
  26032. /**
  26033. * Materials to keep.
  26034. */
  26035. this.materials = new Array();
  26036. /**
  26037. * MorphTargetManagers to keep.
  26038. */
  26039. this.morphTargetManagers = new Array();
  26040. /**
  26041. * Geometries to keep.
  26042. */
  26043. this.geometries = new Array();
  26044. /**
  26045. * TransformNodes to keep.
  26046. */
  26047. this.transformNodes = new Array();
  26048. /**
  26049. * LensFlareSystems to keep.
  26050. */
  26051. this.lensFlareSystems = new Array();
  26052. /**
  26053. * ShadowGenerators to keep.
  26054. */
  26055. this.shadowGenerators = new Array();
  26056. /**
  26057. * ActionManagers to keep.
  26058. */
  26059. this.actionManagers = new Array();
  26060. /**
  26061. * Sounds to keep.
  26062. */
  26063. this.sounds = new Array();
  26064. }
  26065. return KeepAssets;
  26066. }());
  26067. BABYLON.KeepAssets = KeepAssets;
  26068. /**
  26069. * Container with a set of assets that can be added or removed from a scene.
  26070. */
  26071. var AssetContainer = /** @class */ (function () {
  26072. /**
  26073. * Instantiates an AssetContainer.
  26074. * @param scene The scene the AssetContainer belongs to.
  26075. */
  26076. function AssetContainer(scene) {
  26077. // Objects
  26078. /**
  26079. * Cameras populated in the container.
  26080. */
  26081. this.cameras = new Array();
  26082. /**
  26083. * Lights populated in the container.
  26084. */
  26085. this.lights = new Array();
  26086. /**
  26087. * Meshes populated in the container.
  26088. */
  26089. this.meshes = new Array();
  26090. /**
  26091. * Skeletons populated in the container.
  26092. */
  26093. this.skeletons = new Array();
  26094. /**
  26095. * ParticleSystems populated in the container.
  26096. */
  26097. this.particleSystems = new Array();
  26098. /**
  26099. * Animations populated in the container.
  26100. */
  26101. this.animations = new Array();
  26102. /**
  26103. * MultiMaterials populated in the container.
  26104. */
  26105. this.multiMaterials = new Array();
  26106. /**
  26107. * Materials populated in the container.
  26108. */
  26109. this.materials = new Array();
  26110. /**
  26111. * MorphTargetManagers populated in the container.
  26112. */
  26113. this.morphTargetManagers = new Array();
  26114. /**
  26115. * Geometries populated in the container.
  26116. */
  26117. this.geometries = new Array();
  26118. /**
  26119. * TransformNodes populated in the container.
  26120. */
  26121. this.transformNodes = new Array();
  26122. /**
  26123. * LensFlareSystems populated in the container.
  26124. */
  26125. this.lensFlareSystems = new Array();
  26126. /**
  26127. * ShadowGenerators populated in the container.
  26128. */
  26129. this.shadowGenerators = new Array();
  26130. /**
  26131. * ActionManagers populated in the container.
  26132. */
  26133. this.actionManagers = new Array();
  26134. /**
  26135. * Sounds populated in the container.
  26136. */
  26137. this.sounds = new Array();
  26138. this.scene = scene;
  26139. }
  26140. /**
  26141. * Adds all the assets from the container to the scene.
  26142. */
  26143. AssetContainer.prototype.addAllToScene = function () {
  26144. var _this = this;
  26145. this.cameras.forEach(function (o) {
  26146. _this.scene.addCamera(o);
  26147. });
  26148. this.lights.forEach(function (o) {
  26149. _this.scene.addLight(o);
  26150. });
  26151. this.meshes.forEach(function (o) {
  26152. _this.scene.addMesh(o);
  26153. });
  26154. this.skeletons.forEach(function (o) {
  26155. _this.scene.addSkeleton(o);
  26156. });
  26157. this.particleSystems.forEach(function (o) {
  26158. _this.scene.addParticleSystem(o);
  26159. });
  26160. this.animations.forEach(function (o) {
  26161. _this.scene.addAnimation(o);
  26162. });
  26163. this.multiMaterials.forEach(function (o) {
  26164. _this.scene.addMultiMaterial(o);
  26165. });
  26166. this.materials.forEach(function (o) {
  26167. _this.scene.addMaterial(o);
  26168. });
  26169. this.morphTargetManagers.forEach(function (o) {
  26170. _this.scene.addMorphTargetManager(o);
  26171. });
  26172. this.geometries.forEach(function (o) {
  26173. _this.scene.addGeometry(o);
  26174. });
  26175. this.transformNodes.forEach(function (o) {
  26176. _this.scene.addTransformNode(o);
  26177. });
  26178. this.lensFlareSystems.forEach(function (o) {
  26179. _this.scene.addLensFlareSystem(o);
  26180. });
  26181. this.actionManagers.forEach(function (o) {
  26182. _this.scene.addActionManager(o);
  26183. });
  26184. this.sounds.forEach(function (o) {
  26185. o.play();
  26186. o.autoplay = true;
  26187. _this.scene.mainSoundTrack.AddSound(o);
  26188. });
  26189. };
  26190. /**
  26191. * Removes all the assets in the container from the scene
  26192. */
  26193. AssetContainer.prototype.removeAllFromScene = function () {
  26194. var _this = this;
  26195. this.cameras.forEach(function (o) {
  26196. _this.scene.removeCamera(o);
  26197. });
  26198. this.lights.forEach(function (o) {
  26199. _this.scene.removeLight(o);
  26200. });
  26201. this.meshes.forEach(function (o) {
  26202. _this.scene.removeMesh(o);
  26203. });
  26204. this.skeletons.forEach(function (o) {
  26205. _this.scene.removeSkeleton(o);
  26206. });
  26207. this.particleSystems.forEach(function (o) {
  26208. _this.scene.removeParticleSystem(o);
  26209. });
  26210. this.animations.forEach(function (o) {
  26211. _this.scene.removeAnimation(o);
  26212. });
  26213. this.multiMaterials.forEach(function (o) {
  26214. _this.scene.removeMultiMaterial(o);
  26215. });
  26216. this.materials.forEach(function (o) {
  26217. _this.scene.removeMaterial(o);
  26218. });
  26219. this.morphTargetManagers.forEach(function (o) {
  26220. _this.scene.removeMorphTargetManager(o);
  26221. });
  26222. this.geometries.forEach(function (o) {
  26223. _this.scene.removeGeometry(o);
  26224. });
  26225. this.transformNodes.forEach(function (o) {
  26226. _this.scene.removeTransformNode(o);
  26227. });
  26228. this.lensFlareSystems.forEach(function (o) {
  26229. _this.scene.removeLensFlareSystem(o);
  26230. });
  26231. this.actionManagers.forEach(function (o) {
  26232. _this.scene.removeActionManager(o);
  26233. });
  26234. this.sounds.forEach(function (o) {
  26235. o.stop();
  26236. o.autoplay = false;
  26237. _this.scene.mainSoundTrack.RemoveSound(o);
  26238. });
  26239. };
  26240. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26241. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26242. var asset = sourceAssets_1[_i];
  26243. var move = true;
  26244. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26245. var keepAsset = keepAssets_1[_a];
  26246. if (asset === keepAsset) {
  26247. move = false;
  26248. break;
  26249. }
  26250. }
  26251. if (move) {
  26252. targetAssets.push(asset);
  26253. }
  26254. }
  26255. };
  26256. /**
  26257. * Removes all the assets contained in the scene and adds them to the container.
  26258. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26259. */
  26260. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26261. if (keepAssets === undefined) {
  26262. keepAssets = new KeepAssets();
  26263. }
  26264. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26265. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26266. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26267. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26268. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26269. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26270. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26271. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26272. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26273. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26274. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26275. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26276. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26277. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26278. this.removeAllFromScene();
  26279. };
  26280. return AssetContainer;
  26281. }());
  26282. BABYLON.AssetContainer = AssetContainer;
  26283. })(BABYLON || (BABYLON = {}));
  26284. //# sourceMappingURL=babylon.assetContainer.js.map
  26285. "use strict";
  26286. var BABYLON;
  26287. (function (BABYLON) {
  26288. var Buffer = /** @class */ (function () {
  26289. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26290. if (instanced === void 0) { instanced = false; }
  26291. if (engine instanceof BABYLON.Mesh) {
  26292. this._engine = engine.getScene().getEngine();
  26293. }
  26294. else {
  26295. this._engine = engine;
  26296. }
  26297. this._updatable = updatable;
  26298. this._instanced = instanced;
  26299. this._data = data;
  26300. this._strideSize = stride;
  26301. if (!postponeInternalCreation) {
  26302. this.create();
  26303. }
  26304. }
  26305. /**
  26306. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26307. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26308. * @param offset defines offset in the buffer (0 by default)
  26309. * @param size defines the size in floats of attributes (position is 3 for instance)
  26310. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26311. * @param instanced defines if the vertex buffer contains indexed data
  26312. * @returns the new vertex buffer
  26313. */
  26314. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26315. // a lot of these parameters are ignored as they are overriden by the buffer
  26316. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26317. };
  26318. // Properties
  26319. Buffer.prototype.isUpdatable = function () {
  26320. return this._updatable;
  26321. };
  26322. Buffer.prototype.getData = function () {
  26323. return this._data;
  26324. };
  26325. Buffer.prototype.getBuffer = function () {
  26326. return this._buffer;
  26327. };
  26328. Buffer.prototype.getStrideSize = function () {
  26329. return this._strideSize;
  26330. };
  26331. // public getIsInstanced(): boolean {
  26332. // return this._instanced;
  26333. // }
  26334. // public get instanceDivisor(): number {
  26335. // return this._instanceDivisor;
  26336. // }
  26337. // public set instanceDivisor(value: number) {
  26338. // this._instanceDivisor = value;
  26339. // if (value == 0) {
  26340. // this._instanced = false;
  26341. // } else {
  26342. // this._instanced = true;
  26343. // }
  26344. // }
  26345. // Methods
  26346. Buffer.prototype.create = function (data) {
  26347. if (data === void 0) { data = null; }
  26348. if (!data && this._buffer) {
  26349. return; // nothing to do
  26350. }
  26351. data = data || this._data;
  26352. if (!data) {
  26353. return;
  26354. }
  26355. if (!this._buffer) {
  26356. if (this._updatable) {
  26357. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26358. this._data = data;
  26359. }
  26360. else {
  26361. this._buffer = this._engine.createVertexBuffer(data);
  26362. }
  26363. }
  26364. else if (this._updatable) {
  26365. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26366. this._data = data;
  26367. }
  26368. };
  26369. Buffer.prototype._rebuild = function () {
  26370. this._buffer = null;
  26371. this.create(this._data);
  26372. };
  26373. Buffer.prototype.update = function (data) {
  26374. this.create(data);
  26375. };
  26376. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26377. if (!this._buffer) {
  26378. return;
  26379. }
  26380. if (this._updatable) {
  26381. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26382. this._data = null;
  26383. }
  26384. };
  26385. Buffer.prototype.dispose = function () {
  26386. if (!this._buffer) {
  26387. return;
  26388. }
  26389. if (this._engine._releaseBuffer(this._buffer)) {
  26390. this._buffer = null;
  26391. }
  26392. };
  26393. return Buffer;
  26394. }());
  26395. BABYLON.Buffer = Buffer;
  26396. })(BABYLON || (BABYLON = {}));
  26397. //# sourceMappingURL=babylon.buffer.js.map
  26398. "use strict";
  26399. var BABYLON;
  26400. (function (BABYLON) {
  26401. var VertexBuffer = /** @class */ (function () {
  26402. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26403. if (data instanceof BABYLON.Buffer) {
  26404. if (!stride) {
  26405. stride = data.getStrideSize();
  26406. }
  26407. this._buffer = data;
  26408. this._ownsBuffer = false;
  26409. }
  26410. else {
  26411. if (!stride) {
  26412. stride = VertexBuffer.DeduceStride(kind);
  26413. }
  26414. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26415. this._ownsBuffer = true;
  26416. }
  26417. this._stride = stride;
  26418. this._instanced = instanced !== undefined ? instanced : false;
  26419. this._instanceDivisor = instanced ? 1 : 0;
  26420. this._offset = offset ? offset : 0;
  26421. this._size = size ? size : stride;
  26422. this._kind = kind;
  26423. }
  26424. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26425. /**
  26426. * Gets or sets the instance divisor when in instanced mode
  26427. */
  26428. get: function () {
  26429. return this._instanceDivisor;
  26430. },
  26431. set: function (value) {
  26432. this._instanceDivisor = value;
  26433. if (value == 0) {
  26434. this._instanced = false;
  26435. }
  26436. else {
  26437. this._instanced = true;
  26438. }
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. VertexBuffer.prototype._rebuild = function () {
  26444. if (!this._buffer) {
  26445. return;
  26446. }
  26447. this._buffer._rebuild();
  26448. };
  26449. /**
  26450. * Returns the kind of the VertexBuffer (string).
  26451. */
  26452. VertexBuffer.prototype.getKind = function () {
  26453. return this._kind;
  26454. };
  26455. // Properties
  26456. /**
  26457. * Boolean : is the VertexBuffer updatable ?
  26458. */
  26459. VertexBuffer.prototype.isUpdatable = function () {
  26460. return this._buffer.isUpdatable();
  26461. };
  26462. /**
  26463. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26464. */
  26465. VertexBuffer.prototype.getData = function () {
  26466. return this._buffer.getData();
  26467. };
  26468. /**
  26469. * Returns the WebGLBuffer associated to the VertexBuffer.
  26470. */
  26471. VertexBuffer.prototype.getBuffer = function () {
  26472. return this._buffer.getBuffer();
  26473. };
  26474. /**
  26475. * Returns the stride of the VertexBuffer (integer).
  26476. */
  26477. VertexBuffer.prototype.getStrideSize = function () {
  26478. return this._stride;
  26479. };
  26480. /**
  26481. * Returns the offset (integer).
  26482. */
  26483. VertexBuffer.prototype.getOffset = function () {
  26484. return this._offset;
  26485. };
  26486. /**
  26487. * Returns the VertexBuffer total size (integer).
  26488. */
  26489. VertexBuffer.prototype.getSize = function () {
  26490. return this._size;
  26491. };
  26492. /**
  26493. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26494. */
  26495. VertexBuffer.prototype.getIsInstanced = function () {
  26496. return this._instanced;
  26497. };
  26498. /**
  26499. * Returns the instancing divisor, zero for non-instanced (integer).
  26500. */
  26501. VertexBuffer.prototype.getInstanceDivisor = function () {
  26502. return this._instanceDivisor;
  26503. };
  26504. // Methods
  26505. /**
  26506. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26507. * Returns the created WebGLBuffer.
  26508. */
  26509. VertexBuffer.prototype.create = function (data) {
  26510. return this._buffer.create(data);
  26511. };
  26512. /**
  26513. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26514. * This function will create a new buffer if the current one is not updatable
  26515. * Returns the updated WebGLBuffer.
  26516. */
  26517. VertexBuffer.prototype.update = function (data) {
  26518. return this._buffer.update(data);
  26519. };
  26520. /**
  26521. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26522. * Returns the directly updated WebGLBuffer.
  26523. */
  26524. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26525. return this._buffer.updateDirectly(data, offset);
  26526. };
  26527. /**
  26528. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26529. */
  26530. VertexBuffer.prototype.dispose = function () {
  26531. if (this._ownsBuffer) {
  26532. this._buffer.dispose();
  26533. }
  26534. };
  26535. Object.defineProperty(VertexBuffer, "PositionKind", {
  26536. get: function () {
  26537. return VertexBuffer._PositionKind;
  26538. },
  26539. enumerable: true,
  26540. configurable: true
  26541. });
  26542. Object.defineProperty(VertexBuffer, "NormalKind", {
  26543. get: function () {
  26544. return VertexBuffer._NormalKind;
  26545. },
  26546. enumerable: true,
  26547. configurable: true
  26548. });
  26549. Object.defineProperty(VertexBuffer, "TangentKind", {
  26550. get: function () {
  26551. return VertexBuffer._TangentKind;
  26552. },
  26553. enumerable: true,
  26554. configurable: true
  26555. });
  26556. Object.defineProperty(VertexBuffer, "UVKind", {
  26557. get: function () {
  26558. return VertexBuffer._UVKind;
  26559. },
  26560. enumerable: true,
  26561. configurable: true
  26562. });
  26563. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26564. get: function () {
  26565. return VertexBuffer._UV2Kind;
  26566. },
  26567. enumerable: true,
  26568. configurable: true
  26569. });
  26570. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26571. get: function () {
  26572. return VertexBuffer._UV3Kind;
  26573. },
  26574. enumerable: true,
  26575. configurable: true
  26576. });
  26577. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26578. get: function () {
  26579. return VertexBuffer._UV4Kind;
  26580. },
  26581. enumerable: true,
  26582. configurable: true
  26583. });
  26584. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26585. get: function () {
  26586. return VertexBuffer._UV5Kind;
  26587. },
  26588. enumerable: true,
  26589. configurable: true
  26590. });
  26591. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26592. get: function () {
  26593. return VertexBuffer._UV6Kind;
  26594. },
  26595. enumerable: true,
  26596. configurable: true
  26597. });
  26598. Object.defineProperty(VertexBuffer, "ColorKind", {
  26599. get: function () {
  26600. return VertexBuffer._ColorKind;
  26601. },
  26602. enumerable: true,
  26603. configurable: true
  26604. });
  26605. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26606. get: function () {
  26607. return VertexBuffer._MatricesIndicesKind;
  26608. },
  26609. enumerable: true,
  26610. configurable: true
  26611. });
  26612. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26613. get: function () {
  26614. return VertexBuffer._MatricesWeightsKind;
  26615. },
  26616. enumerable: true,
  26617. configurable: true
  26618. });
  26619. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26620. get: function () {
  26621. return VertexBuffer._MatricesIndicesExtraKind;
  26622. },
  26623. enumerable: true,
  26624. configurable: true
  26625. });
  26626. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26627. get: function () {
  26628. return VertexBuffer._MatricesWeightsExtraKind;
  26629. },
  26630. enumerable: true,
  26631. configurable: true
  26632. });
  26633. /**
  26634. * Deduces the stride given a kind.
  26635. * @param kind The kind string to deduce
  26636. * @returns The deduced stride
  26637. */
  26638. VertexBuffer.DeduceStride = function (kind) {
  26639. switch (kind) {
  26640. case VertexBuffer.UVKind:
  26641. case VertexBuffer.UV2Kind:
  26642. case VertexBuffer.UV3Kind:
  26643. case VertexBuffer.UV4Kind:
  26644. case VertexBuffer.UV5Kind:
  26645. case VertexBuffer.UV6Kind:
  26646. return 2;
  26647. case VertexBuffer.NormalKind:
  26648. case VertexBuffer.PositionKind:
  26649. return 3;
  26650. case VertexBuffer.ColorKind:
  26651. case VertexBuffer.MatricesIndicesKind:
  26652. case VertexBuffer.MatricesIndicesExtraKind:
  26653. case VertexBuffer.MatricesWeightsKind:
  26654. case VertexBuffer.MatricesWeightsExtraKind:
  26655. case VertexBuffer.TangentKind:
  26656. return 4;
  26657. default:
  26658. throw new Error("Invalid kind '" + kind + "'");
  26659. }
  26660. };
  26661. // Enums
  26662. VertexBuffer._PositionKind = "position";
  26663. VertexBuffer._NormalKind = "normal";
  26664. VertexBuffer._TangentKind = "tangent";
  26665. VertexBuffer._UVKind = "uv";
  26666. VertexBuffer._UV2Kind = "uv2";
  26667. VertexBuffer._UV3Kind = "uv3";
  26668. VertexBuffer._UV4Kind = "uv4";
  26669. VertexBuffer._UV5Kind = "uv5";
  26670. VertexBuffer._UV6Kind = "uv6";
  26671. VertexBuffer._ColorKind = "color";
  26672. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26673. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26674. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26675. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26676. return VertexBuffer;
  26677. }());
  26678. BABYLON.VertexBuffer = VertexBuffer;
  26679. })(BABYLON || (BABYLON = {}));
  26680. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26681. "use strict";
  26682. var BABYLON;
  26683. (function (BABYLON) {
  26684. /**
  26685. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26686. */
  26687. var DummyInternalTextureTracker = /** @class */ (function () {
  26688. function DummyInternalTextureTracker() {
  26689. /**
  26690. * Gets or set the previous tracker in the list
  26691. */
  26692. this.previous = null;
  26693. /**
  26694. * Gets or set the next tracker in the list
  26695. */
  26696. this.next = null;
  26697. }
  26698. return DummyInternalTextureTracker;
  26699. }());
  26700. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26701. })(BABYLON || (BABYLON = {}));
  26702. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26703. "use strict";
  26704. var BABYLON;
  26705. (function (BABYLON) {
  26706. /**
  26707. * Class used to store data associated with WebGL texture data for the engine
  26708. * This class should not be used directly
  26709. */
  26710. var InternalTexture = /** @class */ (function () {
  26711. /**
  26712. * Creates a new InternalTexture
  26713. * @param engine defines the engine to use
  26714. * @param dataSource defines the type of data that will be used
  26715. */
  26716. function InternalTexture(engine, dataSource) {
  26717. /**
  26718. * Observable called when the texture is loaded
  26719. */
  26720. this.onLoadedObservable = new BABYLON.Observable();
  26721. /**
  26722. * Gets or set the previous tracker in the list
  26723. */
  26724. this.previous = null;
  26725. /**
  26726. * Gets or set the next tracker in the list
  26727. */
  26728. this.next = null;
  26729. // Private
  26730. /** @ignore */
  26731. this._initialSlot = -1;
  26732. /** @ignore */
  26733. this._designatedSlot = -1;
  26734. /** @ignore */
  26735. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26736. /** @ignore */
  26737. this._comparisonFunction = 0;
  26738. /** @ignore */
  26739. this._references = 1;
  26740. this._engine = engine;
  26741. this._dataSource = dataSource;
  26742. this._webGLTexture = engine._createTexture();
  26743. }
  26744. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26745. /**
  26746. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26747. */
  26748. get: function () {
  26749. return this._dataSource;
  26750. },
  26751. enumerable: true,
  26752. configurable: true
  26753. });
  26754. /**
  26755. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26756. */
  26757. InternalTexture.prototype.incrementReferences = function () {
  26758. this._references++;
  26759. };
  26760. /**
  26761. * Change the size of the texture (not the size of the content)
  26762. * @param width defines the new width
  26763. * @param height defines the new height
  26764. * @param depth defines the new depth (1 by default)
  26765. */
  26766. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26767. if (depth === void 0) { depth = 1; }
  26768. this.width = width;
  26769. this.height = height;
  26770. this.depth = depth;
  26771. this.baseWidth = width;
  26772. this.baseHeight = height;
  26773. this.baseDepth = depth;
  26774. this._size = width * height * depth;
  26775. };
  26776. /** @ignore */
  26777. InternalTexture.prototype._rebuild = function () {
  26778. var _this = this;
  26779. var proxy;
  26780. this.isReady = false;
  26781. this._cachedCoordinatesMode = null;
  26782. this._cachedWrapU = null;
  26783. this._cachedWrapV = null;
  26784. this._cachedAnisotropicFilteringLevel = null;
  26785. switch (this._dataSource) {
  26786. case InternalTexture.DATASOURCE_TEMP:
  26787. return;
  26788. case InternalTexture.DATASOURCE_URL:
  26789. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26790. _this.isReady = true;
  26791. }, null, this._buffer, undefined, this.format);
  26792. proxy._swapAndDie(this);
  26793. return;
  26794. case InternalTexture.DATASOURCE_RAW:
  26795. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26796. proxy._swapAndDie(this);
  26797. this.isReady = true;
  26798. return;
  26799. case InternalTexture.DATASOURCE_RAW3D:
  26800. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26801. proxy._swapAndDie(this);
  26802. this.isReady = true;
  26803. return;
  26804. case InternalTexture.DATASOURCE_DYNAMIC:
  26805. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26806. proxy._swapAndDie(this);
  26807. // The engine will make sure to update content so no need to flag it as isReady = true
  26808. return;
  26809. case InternalTexture.DATASOURCE_RENDERTARGET:
  26810. var options = new BABYLON.RenderTargetCreationOptions();
  26811. options.generateDepthBuffer = this._generateDepthBuffer;
  26812. options.generateMipMaps = this.generateMipMaps;
  26813. options.generateStencilBuffer = this._generateStencilBuffer;
  26814. options.samplingMode = this.samplingMode;
  26815. options.type = this.type;
  26816. if (this.isCube) {
  26817. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26818. }
  26819. else {
  26820. var size = {
  26821. width: this.width,
  26822. height: this.height
  26823. };
  26824. proxy = this._engine.createRenderTargetTexture(size, options);
  26825. }
  26826. proxy._swapAndDie(this);
  26827. this.isReady = true;
  26828. return;
  26829. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26830. var depthTextureOptions = {
  26831. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26832. comparisonFunction: this._comparisonFunction,
  26833. generateStencil: this._generateStencilBuffer,
  26834. isCube: this.isCube
  26835. };
  26836. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26837. proxy._swapAndDie(this);
  26838. this.isReady = true;
  26839. return;
  26840. case InternalTexture.DATASOURCE_CUBE:
  26841. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26842. _this.isReady = true;
  26843. }, null, this.format, this._extension);
  26844. proxy._swapAndDie(this);
  26845. return;
  26846. case InternalTexture.DATASOURCE_CUBERAW:
  26847. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26848. proxy._swapAndDie(this);
  26849. this.isReady = true;
  26850. return;
  26851. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26852. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26853. if (proxy) {
  26854. proxy._swapAndDie(_this);
  26855. }
  26856. _this.isReady = true;
  26857. }, null, this.format, this._extension);
  26858. return;
  26859. }
  26860. };
  26861. InternalTexture.prototype._swapAndDie = function (target) {
  26862. target._webGLTexture = this._webGLTexture;
  26863. if (this._framebuffer) {
  26864. target._framebuffer = this._framebuffer;
  26865. }
  26866. if (this._depthStencilBuffer) {
  26867. target._depthStencilBuffer = this._depthStencilBuffer;
  26868. }
  26869. if (this._lodTextureHigh) {
  26870. if (target._lodTextureHigh) {
  26871. target._lodTextureHigh.dispose();
  26872. }
  26873. target._lodTextureHigh = this._lodTextureHigh;
  26874. }
  26875. if (this._lodTextureMid) {
  26876. if (target._lodTextureMid) {
  26877. target._lodTextureMid.dispose();
  26878. }
  26879. target._lodTextureMid = this._lodTextureMid;
  26880. }
  26881. if (this._lodTextureLow) {
  26882. if (target._lodTextureLow) {
  26883. target._lodTextureLow.dispose();
  26884. }
  26885. target._lodTextureLow = this._lodTextureLow;
  26886. }
  26887. var cache = this._engine.getLoadedTexturesCache();
  26888. var index = cache.indexOf(this);
  26889. if (index !== -1) {
  26890. cache.splice(index, 1);
  26891. }
  26892. };
  26893. /**
  26894. * Dispose the current allocated resources
  26895. */
  26896. InternalTexture.prototype.dispose = function () {
  26897. if (!this._webGLTexture) {
  26898. return;
  26899. }
  26900. this._references--;
  26901. if (this._references === 0) {
  26902. this._engine._releaseTexture(this);
  26903. this._webGLTexture = null;
  26904. this.previous = null;
  26905. this.next = null;
  26906. }
  26907. };
  26908. /**
  26909. * The source of the texture data is unknown
  26910. */
  26911. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26912. /**
  26913. * Texture data comes from an URL
  26914. */
  26915. InternalTexture.DATASOURCE_URL = 1;
  26916. /**
  26917. * Texture data is only used for temporary storage
  26918. */
  26919. InternalTexture.DATASOURCE_TEMP = 2;
  26920. /**
  26921. * Texture data comes from raw data (ArrayBuffer)
  26922. */
  26923. InternalTexture.DATASOURCE_RAW = 3;
  26924. /**
  26925. * Texture content is dynamic (video or dynamic texture)
  26926. */
  26927. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26928. /**
  26929. * Texture content is generated by rendering to it
  26930. */
  26931. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26932. /**
  26933. * Texture content is part of a multi render target process
  26934. */
  26935. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26936. /**
  26937. * Texture data comes from a cube data file
  26938. */
  26939. InternalTexture.DATASOURCE_CUBE = 7;
  26940. /**
  26941. * Texture data comes from a raw cube data
  26942. */
  26943. InternalTexture.DATASOURCE_CUBERAW = 8;
  26944. /**
  26945. * Texture data come from a prefiltered cube data file
  26946. */
  26947. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26948. /**
  26949. * Texture content is raw 3D data
  26950. */
  26951. InternalTexture.DATASOURCE_RAW3D = 10;
  26952. /**
  26953. * Texture content is a depth texture
  26954. */
  26955. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26956. return InternalTexture;
  26957. }());
  26958. BABYLON.InternalTexture = InternalTexture;
  26959. })(BABYLON || (BABYLON = {}));
  26960. //# sourceMappingURL=babylon.internalTexture.js.map
  26961. "use strict";
  26962. var BABYLON;
  26963. (function (BABYLON) {
  26964. var BaseTexture = /** @class */ (function () {
  26965. function BaseTexture(scene) {
  26966. this._hasAlpha = false;
  26967. this.getAlphaFromRGB = false;
  26968. this.level = 1;
  26969. this.coordinatesIndex = 0;
  26970. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26971. /**
  26972. * | Value | Type | Description |
  26973. * | ----- | ------------------ | ----------- |
  26974. * | 0 | CLAMP_ADDRESSMODE | |
  26975. * | 1 | WRAP_ADDRESSMODE | |
  26976. * | 2 | MIRROR_ADDRESSMODE | |
  26977. */
  26978. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26979. /**
  26980. * | Value | Type | Description |
  26981. * | ----- | ------------------ | ----------- |
  26982. * | 0 | CLAMP_ADDRESSMODE | |
  26983. * | 1 | WRAP_ADDRESSMODE | |
  26984. * | 2 | MIRROR_ADDRESSMODE | |
  26985. */
  26986. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26987. /**
  26988. * | Value | Type | Description |
  26989. * | ----- | ------------------ | ----------- |
  26990. * | 0 | CLAMP_ADDRESSMODE | |
  26991. * | 1 | WRAP_ADDRESSMODE | |
  26992. * | 2 | MIRROR_ADDRESSMODE | |
  26993. */
  26994. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26995. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26996. this.isCube = false;
  26997. this.is3D = false;
  26998. this.gammaSpace = true;
  26999. this.invertZ = false;
  27000. this.lodLevelInAlpha = false;
  27001. this.lodGenerationOffset = 0.0;
  27002. this.lodGenerationScale = 0.8;
  27003. this.isRenderTarget = false;
  27004. this.animations = new Array();
  27005. /**
  27006. * An event triggered when the texture is disposed.
  27007. * @type {BABYLON.Observable}
  27008. */
  27009. this.onDisposeObservable = new BABYLON.Observable();
  27010. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27011. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27012. if (this._scene) {
  27013. this._scene.textures.push(this);
  27014. }
  27015. this._uid = null;
  27016. }
  27017. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  27018. get: function () {
  27019. return this._hasAlpha;
  27020. },
  27021. set: function (value) {
  27022. if (this._hasAlpha === value) {
  27023. return;
  27024. }
  27025. this._hasAlpha = value;
  27026. if (this._scene) {
  27027. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  27028. }
  27029. },
  27030. enumerable: true,
  27031. configurable: true
  27032. });
  27033. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27034. get: function () {
  27035. return this._coordinatesMode;
  27036. },
  27037. /**
  27038. * How a texture is mapped.
  27039. *
  27040. * | Value | Type | Description |
  27041. * | ----- | ----------------------------------- | ----------- |
  27042. * | 0 | EXPLICIT_MODE | |
  27043. * | 1 | SPHERICAL_MODE | |
  27044. * | 2 | PLANAR_MODE | |
  27045. * | 3 | CUBIC_MODE | |
  27046. * | 4 | PROJECTION_MODE | |
  27047. * | 5 | SKYBOX_MODE | |
  27048. * | 6 | INVCUBIC_MODE | |
  27049. * | 7 | EQUIRECTANGULAR_MODE | |
  27050. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27051. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27052. */
  27053. set: function (value) {
  27054. if (this._coordinatesMode === value) {
  27055. return;
  27056. }
  27057. this._coordinatesMode = value;
  27058. if (this._scene) {
  27059. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27060. }
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. Object.defineProperty(BaseTexture.prototype, "uid", {
  27066. get: function () {
  27067. if (!this._uid) {
  27068. this._uid = BABYLON.Tools.RandomId();
  27069. }
  27070. return this._uid;
  27071. },
  27072. enumerable: true,
  27073. configurable: true
  27074. });
  27075. BaseTexture.prototype.toString = function () {
  27076. return this.name;
  27077. };
  27078. BaseTexture.prototype.getClassName = function () {
  27079. return "BaseTexture";
  27080. };
  27081. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27082. set: function (callback) {
  27083. if (this._onDisposeObserver) {
  27084. this.onDisposeObservable.remove(this._onDisposeObserver);
  27085. }
  27086. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27087. },
  27088. enumerable: true,
  27089. configurable: true
  27090. });
  27091. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27092. get: function () {
  27093. return true;
  27094. },
  27095. enumerable: true,
  27096. configurable: true
  27097. });
  27098. BaseTexture.prototype.getScene = function () {
  27099. return this._scene;
  27100. };
  27101. BaseTexture.prototype.getTextureMatrix = function () {
  27102. return BABYLON.Matrix.IdentityReadOnly;
  27103. };
  27104. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27105. return BABYLON.Matrix.IdentityReadOnly;
  27106. };
  27107. BaseTexture.prototype.getInternalTexture = function () {
  27108. return this._texture;
  27109. };
  27110. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27111. return !this.isBlocking || this.isReady();
  27112. };
  27113. BaseTexture.prototype.isReady = function () {
  27114. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27115. this.delayLoad();
  27116. return false;
  27117. }
  27118. if (this._texture) {
  27119. return this._texture.isReady;
  27120. }
  27121. return false;
  27122. };
  27123. BaseTexture.prototype.getSize = function () {
  27124. if (this._texture && this._texture.width) {
  27125. return new BABYLON.Size(this._texture.width, this._texture.height);
  27126. }
  27127. if (this._texture && this._texture._size) {
  27128. return new BABYLON.Size(this._texture._size, this._texture._size);
  27129. }
  27130. return BABYLON.Size.Zero();
  27131. };
  27132. BaseTexture.prototype.getBaseSize = function () {
  27133. if (!this.isReady() || !this._texture)
  27134. return BABYLON.Size.Zero();
  27135. if (this._texture._size) {
  27136. return new BABYLON.Size(this._texture._size, this._texture._size);
  27137. }
  27138. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27139. };
  27140. BaseTexture.prototype.scale = function (ratio) {
  27141. };
  27142. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27143. get: function () {
  27144. return false;
  27145. },
  27146. enumerable: true,
  27147. configurable: true
  27148. });
  27149. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27150. if (!this._scene) {
  27151. return null;
  27152. }
  27153. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27154. for (var index = 0; index < texturesCache.length; index++) {
  27155. var texturesCacheEntry = texturesCache[index];
  27156. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27157. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27158. texturesCacheEntry.incrementReferences();
  27159. return texturesCacheEntry;
  27160. }
  27161. }
  27162. }
  27163. return null;
  27164. };
  27165. BaseTexture.prototype._rebuild = function () {
  27166. };
  27167. BaseTexture.prototype.delayLoad = function () {
  27168. };
  27169. BaseTexture.prototype.clone = function () {
  27170. return null;
  27171. };
  27172. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27173. get: function () {
  27174. if (!this._texture) {
  27175. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27176. }
  27177. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27178. },
  27179. enumerable: true,
  27180. configurable: true
  27181. });
  27182. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27183. get: function () {
  27184. if (!this._texture) {
  27185. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27186. }
  27187. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27188. },
  27189. enumerable: true,
  27190. configurable: true
  27191. });
  27192. BaseTexture.prototype.readPixels = function (faceIndex) {
  27193. if (faceIndex === void 0) { faceIndex = 0; }
  27194. if (!this._texture) {
  27195. return null;
  27196. }
  27197. var size = this.getSize();
  27198. var scene = this.getScene();
  27199. if (!scene) {
  27200. return null;
  27201. }
  27202. var engine = scene.getEngine();
  27203. if (this._texture.isCube) {
  27204. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27205. }
  27206. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27207. };
  27208. BaseTexture.prototype.releaseInternalTexture = function () {
  27209. if (this._texture) {
  27210. this._texture.dispose();
  27211. this._texture = null;
  27212. }
  27213. };
  27214. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27215. get: function () {
  27216. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27217. return null;
  27218. }
  27219. if (!this._texture._sphericalPolynomial) {
  27220. this._texture._sphericalPolynomial =
  27221. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27222. }
  27223. return this._texture._sphericalPolynomial;
  27224. },
  27225. set: function (value) {
  27226. if (this._texture) {
  27227. this._texture._sphericalPolynomial = value;
  27228. }
  27229. },
  27230. enumerable: true,
  27231. configurable: true
  27232. });
  27233. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27234. get: function () {
  27235. if (this._texture) {
  27236. return this._texture._lodTextureHigh;
  27237. }
  27238. return null;
  27239. },
  27240. enumerable: true,
  27241. configurable: true
  27242. });
  27243. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27244. get: function () {
  27245. if (this._texture) {
  27246. return this._texture._lodTextureMid;
  27247. }
  27248. return null;
  27249. },
  27250. enumerable: true,
  27251. configurable: true
  27252. });
  27253. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27254. get: function () {
  27255. if (this._texture) {
  27256. return this._texture._lodTextureLow;
  27257. }
  27258. return null;
  27259. },
  27260. enumerable: true,
  27261. configurable: true
  27262. });
  27263. BaseTexture.prototype.dispose = function () {
  27264. if (!this._scene) {
  27265. return;
  27266. }
  27267. // Animations
  27268. this._scene.stopAnimation(this);
  27269. // Remove from scene
  27270. this._scene._removePendingData(this);
  27271. var index = this._scene.textures.indexOf(this);
  27272. if (index >= 0) {
  27273. this._scene.textures.splice(index, 1);
  27274. }
  27275. if (this._texture === undefined) {
  27276. return;
  27277. }
  27278. // Release
  27279. this.releaseInternalTexture();
  27280. // Callback
  27281. this.onDisposeObservable.notifyObservers(this);
  27282. this.onDisposeObservable.clear();
  27283. };
  27284. BaseTexture.prototype.serialize = function () {
  27285. if (!this.name) {
  27286. return null;
  27287. }
  27288. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27289. // Animations
  27290. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27291. return serializationObject;
  27292. };
  27293. BaseTexture.WhenAllReady = function (textures, callback) {
  27294. var numRemaining = textures.length;
  27295. if (numRemaining === 0) {
  27296. callback();
  27297. return;
  27298. }
  27299. var _loop_1 = function () {
  27300. texture = textures[i];
  27301. if (texture.isReady()) {
  27302. if (--numRemaining === 0) {
  27303. callback();
  27304. }
  27305. }
  27306. else {
  27307. onLoadObservable = texture.onLoadObservable;
  27308. var onLoadCallback_1 = function () {
  27309. onLoadObservable.removeCallback(onLoadCallback_1);
  27310. if (--numRemaining === 0) {
  27311. callback();
  27312. }
  27313. };
  27314. onLoadObservable.add(onLoadCallback_1);
  27315. }
  27316. };
  27317. var texture, onLoadObservable;
  27318. for (var i = 0; i < textures.length; i++) {
  27319. _loop_1();
  27320. }
  27321. };
  27322. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27323. __decorate([
  27324. BABYLON.serialize()
  27325. ], BaseTexture.prototype, "name", void 0);
  27326. __decorate([
  27327. BABYLON.serialize("hasAlpha")
  27328. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27329. __decorate([
  27330. BABYLON.serialize()
  27331. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27332. __decorate([
  27333. BABYLON.serialize()
  27334. ], BaseTexture.prototype, "level", void 0);
  27335. __decorate([
  27336. BABYLON.serialize()
  27337. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27338. __decorate([
  27339. BABYLON.serialize("coordinatesMode")
  27340. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27341. __decorate([
  27342. BABYLON.serialize()
  27343. ], BaseTexture.prototype, "wrapU", void 0);
  27344. __decorate([
  27345. BABYLON.serialize()
  27346. ], BaseTexture.prototype, "wrapV", void 0);
  27347. __decorate([
  27348. BABYLON.serialize()
  27349. ], BaseTexture.prototype, "wrapR", void 0);
  27350. __decorate([
  27351. BABYLON.serialize()
  27352. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27353. __decorate([
  27354. BABYLON.serialize()
  27355. ], BaseTexture.prototype, "isCube", void 0);
  27356. __decorate([
  27357. BABYLON.serialize()
  27358. ], BaseTexture.prototype, "is3D", void 0);
  27359. __decorate([
  27360. BABYLON.serialize()
  27361. ], BaseTexture.prototype, "gammaSpace", void 0);
  27362. __decorate([
  27363. BABYLON.serialize()
  27364. ], BaseTexture.prototype, "invertZ", void 0);
  27365. __decorate([
  27366. BABYLON.serialize()
  27367. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27368. __decorate([
  27369. BABYLON.serialize()
  27370. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27371. __decorate([
  27372. BABYLON.serialize()
  27373. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27374. __decorate([
  27375. BABYLON.serialize()
  27376. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27377. return BaseTexture;
  27378. }());
  27379. BABYLON.BaseTexture = BaseTexture;
  27380. })(BABYLON || (BABYLON = {}));
  27381. //# sourceMappingURL=babylon.baseTexture.js.map
  27382. "use strict";
  27383. var BABYLON;
  27384. (function (BABYLON) {
  27385. var Texture = /** @class */ (function (_super) {
  27386. __extends(Texture, _super);
  27387. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27388. if (noMipmap === void 0) { noMipmap = false; }
  27389. if (invertY === void 0) { invertY = true; }
  27390. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27391. if (onLoad === void 0) { onLoad = null; }
  27392. if (onError === void 0) { onError = null; }
  27393. if (buffer === void 0) { buffer = null; }
  27394. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27395. var _this = _super.call(this, scene) || this;
  27396. _this.uOffset = 0;
  27397. _this.vOffset = 0;
  27398. _this.uScale = 1.0;
  27399. _this.vScale = 1.0;
  27400. _this.uAng = 0;
  27401. _this.vAng = 0;
  27402. _this.wAng = 0;
  27403. _this._isBlocking = true;
  27404. _this.name = url || "";
  27405. _this.url = url;
  27406. _this._noMipmap = noMipmap;
  27407. _this._invertY = invertY;
  27408. _this._samplingMode = samplingMode;
  27409. _this._buffer = buffer;
  27410. _this._deleteBuffer = deleteBuffer;
  27411. if (format) {
  27412. _this._format = format;
  27413. }
  27414. scene = _this.getScene();
  27415. if (!scene) {
  27416. return _this;
  27417. }
  27418. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27419. var load = function () {
  27420. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27421. _this.onLoadObservable.notifyObservers(_this);
  27422. }
  27423. if (onLoad) {
  27424. onLoad();
  27425. }
  27426. if (!_this.isBlocking && scene) {
  27427. scene.resetCachedMaterial();
  27428. }
  27429. };
  27430. if (!_this.url) {
  27431. _this._delayedOnLoad = load;
  27432. _this._delayedOnError = onError;
  27433. return _this;
  27434. }
  27435. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27436. if (!_this._texture) {
  27437. if (!scene.useDelayedTextureLoading) {
  27438. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27439. if (deleteBuffer) {
  27440. delete _this._buffer;
  27441. }
  27442. }
  27443. else {
  27444. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27445. _this._delayedOnLoad = load;
  27446. _this._delayedOnError = onError;
  27447. }
  27448. }
  27449. else {
  27450. if (_this._texture.isReady) {
  27451. BABYLON.Tools.SetImmediate(function () { return load(); });
  27452. }
  27453. else {
  27454. _this._texture.onLoadedObservable.add(load);
  27455. }
  27456. }
  27457. return _this;
  27458. }
  27459. Object.defineProperty(Texture.prototype, "noMipmap", {
  27460. get: function () {
  27461. return this._noMipmap;
  27462. },
  27463. enumerable: true,
  27464. configurable: true
  27465. });
  27466. Object.defineProperty(Texture.prototype, "isBlocking", {
  27467. get: function () {
  27468. return this._isBlocking;
  27469. },
  27470. set: function (value) {
  27471. this._isBlocking = value;
  27472. },
  27473. enumerable: true,
  27474. configurable: true
  27475. });
  27476. Object.defineProperty(Texture.prototype, "samplingMode", {
  27477. get: function () {
  27478. return this._samplingMode;
  27479. },
  27480. enumerable: true,
  27481. configurable: true
  27482. });
  27483. Texture.prototype.updateURL = function (url) {
  27484. this.url = url;
  27485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27486. this.delayLoad();
  27487. };
  27488. Texture.prototype.delayLoad = function () {
  27489. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27490. return;
  27491. }
  27492. var scene = this.getScene();
  27493. if (!scene) {
  27494. return;
  27495. }
  27496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27497. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27498. if (!this._texture) {
  27499. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27500. if (this._deleteBuffer) {
  27501. delete this._buffer;
  27502. }
  27503. }
  27504. else {
  27505. if (this._delayedOnLoad) {
  27506. if (this._texture.isReady) {
  27507. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27508. }
  27509. else {
  27510. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27511. }
  27512. }
  27513. }
  27514. this._delayedOnLoad = null;
  27515. this._delayedOnError = null;
  27516. };
  27517. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27518. if (!this._texture) {
  27519. return;
  27520. }
  27521. var scene = this.getScene();
  27522. if (!scene) {
  27523. return;
  27524. }
  27525. this._samplingMode = samplingMode;
  27526. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27527. };
  27528. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27529. x *= this.uScale;
  27530. y *= this.vScale;
  27531. x -= 0.5 * this.uScale;
  27532. y -= 0.5 * this.vScale;
  27533. z -= 0.5;
  27534. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27535. t.x += 0.5 * this.uScale + this.uOffset;
  27536. t.y += 0.5 * this.vScale + this.vOffset;
  27537. t.z += 0.5;
  27538. };
  27539. Texture.prototype.getTextureMatrix = function () {
  27540. var _this = this;
  27541. if (this.uOffset === this._cachedUOffset &&
  27542. this.vOffset === this._cachedVOffset &&
  27543. this.uScale === this._cachedUScale &&
  27544. this.vScale === this._cachedVScale &&
  27545. this.uAng === this._cachedUAng &&
  27546. this.vAng === this._cachedVAng &&
  27547. this.wAng === this._cachedWAng) {
  27548. return this._cachedTextureMatrix;
  27549. }
  27550. this._cachedUOffset = this.uOffset;
  27551. this._cachedVOffset = this.vOffset;
  27552. this._cachedUScale = this.uScale;
  27553. this._cachedVScale = this.vScale;
  27554. this._cachedUAng = this.uAng;
  27555. this._cachedVAng = this.vAng;
  27556. this._cachedWAng = this.wAng;
  27557. if (!this._cachedTextureMatrix) {
  27558. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27559. this._rowGenerationMatrix = new BABYLON.Matrix();
  27560. this._t0 = BABYLON.Vector3.Zero();
  27561. this._t1 = BABYLON.Vector3.Zero();
  27562. this._t2 = BABYLON.Vector3.Zero();
  27563. }
  27564. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27565. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27566. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27567. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27568. this._t1.subtractInPlace(this._t0);
  27569. this._t2.subtractInPlace(this._t0);
  27570. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27571. this._cachedTextureMatrix.m[0] = this._t1.x;
  27572. this._cachedTextureMatrix.m[1] = this._t1.y;
  27573. this._cachedTextureMatrix.m[2] = this._t1.z;
  27574. this._cachedTextureMatrix.m[4] = this._t2.x;
  27575. this._cachedTextureMatrix.m[5] = this._t2.y;
  27576. this._cachedTextureMatrix.m[6] = this._t2.z;
  27577. this._cachedTextureMatrix.m[8] = this._t0.x;
  27578. this._cachedTextureMatrix.m[9] = this._t0.y;
  27579. this._cachedTextureMatrix.m[10] = this._t0.z;
  27580. var scene = this.getScene();
  27581. if (!scene) {
  27582. return this._cachedTextureMatrix;
  27583. }
  27584. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27585. return mat.hasTexture(_this);
  27586. });
  27587. return this._cachedTextureMatrix;
  27588. };
  27589. Texture.prototype.getReflectionTextureMatrix = function () {
  27590. var _this = this;
  27591. var scene = this.getScene();
  27592. if (!scene) {
  27593. return this._cachedTextureMatrix;
  27594. }
  27595. if (this.uOffset === this._cachedUOffset &&
  27596. this.vOffset === this._cachedVOffset &&
  27597. this.uScale === this._cachedUScale &&
  27598. this.vScale === this._cachedVScale &&
  27599. this.coordinatesMode === this._cachedCoordinatesMode) {
  27600. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27601. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27602. return this._cachedTextureMatrix;
  27603. }
  27604. }
  27605. else {
  27606. return this._cachedTextureMatrix;
  27607. }
  27608. }
  27609. if (!this._cachedTextureMatrix) {
  27610. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27611. }
  27612. if (!this._projectionModeMatrix) {
  27613. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27614. }
  27615. this._cachedUOffset = this.uOffset;
  27616. this._cachedVOffset = this.vOffset;
  27617. this._cachedUScale = this.uScale;
  27618. this._cachedVScale = this.vScale;
  27619. this._cachedCoordinatesMode = this.coordinatesMode;
  27620. switch (this.coordinatesMode) {
  27621. case Texture.PLANAR_MODE:
  27622. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27623. this._cachedTextureMatrix[0] = this.uScale;
  27624. this._cachedTextureMatrix[5] = this.vScale;
  27625. this._cachedTextureMatrix[12] = this.uOffset;
  27626. this._cachedTextureMatrix[13] = this.vOffset;
  27627. break;
  27628. case Texture.PROJECTION_MODE:
  27629. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27630. this._projectionModeMatrix.m[0] = 0.5;
  27631. this._projectionModeMatrix.m[5] = -0.5;
  27632. this._projectionModeMatrix.m[10] = 0.0;
  27633. this._projectionModeMatrix.m[12] = 0.5;
  27634. this._projectionModeMatrix.m[13] = 0.5;
  27635. this._projectionModeMatrix.m[14] = 1.0;
  27636. this._projectionModeMatrix.m[15] = 1.0;
  27637. var projectionMatrix = scene.getProjectionMatrix();
  27638. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27639. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27640. break;
  27641. default:
  27642. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27643. break;
  27644. }
  27645. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27646. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27647. });
  27648. return this._cachedTextureMatrix;
  27649. };
  27650. Texture.prototype.clone = function () {
  27651. var _this = this;
  27652. return BABYLON.SerializationHelper.Clone(function () {
  27653. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27654. }, this);
  27655. };
  27656. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27657. get: function () {
  27658. if (!this._onLoadObservable) {
  27659. this._onLoadObservable = new BABYLON.Observable();
  27660. }
  27661. return this._onLoadObservable;
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. Texture.prototype.serialize = function () {
  27667. var serializationObject = _super.prototype.serialize.call(this);
  27668. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27669. serializationObject.base64String = this._buffer;
  27670. serializationObject.name = serializationObject.name.replace("data:", "");
  27671. }
  27672. return serializationObject;
  27673. };
  27674. Texture.prototype.getClassName = function () {
  27675. return "Texture";
  27676. };
  27677. Texture.prototype.dispose = function () {
  27678. _super.prototype.dispose.call(this);
  27679. if (this.onLoadObservable) {
  27680. this.onLoadObservable.clear();
  27681. this._onLoadObservable = null;
  27682. }
  27683. this._delayedOnLoad = null;
  27684. this._delayedOnError = null;
  27685. };
  27686. // Statics
  27687. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27688. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27689. if (onLoad === void 0) { onLoad = null; }
  27690. if (onError === void 0) { onError = null; }
  27691. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27692. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27693. };
  27694. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27695. if (parsedTexture.customType) {
  27696. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27697. // Update Sampling Mode
  27698. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27699. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27700. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27701. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27702. }
  27703. }
  27704. return parsedCustomTexture;
  27705. }
  27706. if (parsedTexture.isCube) {
  27707. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27708. }
  27709. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27710. return null;
  27711. }
  27712. var texture = BABYLON.SerializationHelper.Parse(function () {
  27713. var generateMipMaps = true;
  27714. if (parsedTexture.noMipmap) {
  27715. generateMipMaps = false;
  27716. }
  27717. if (parsedTexture.mirrorPlane) {
  27718. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27719. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27720. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27721. return mirrorTexture;
  27722. }
  27723. else if (parsedTexture.isRenderTarget) {
  27724. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27725. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27726. return renderTargetTexture;
  27727. }
  27728. else {
  27729. var texture;
  27730. if (parsedTexture.base64String) {
  27731. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27732. }
  27733. else {
  27734. var url = rootUrl + parsedTexture.name;
  27735. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27736. url = parsedTexture.url;
  27737. }
  27738. texture = new Texture(url, scene, !generateMipMaps);
  27739. }
  27740. return texture;
  27741. }
  27742. }, parsedTexture, scene);
  27743. // Update Sampling Mode
  27744. if (parsedTexture.samplingMode) {
  27745. var sampling = parsedTexture.samplingMode;
  27746. if (texture._samplingMode !== sampling) {
  27747. texture.updateSamplingMode(sampling);
  27748. }
  27749. }
  27750. // Animations
  27751. if (parsedTexture.animations) {
  27752. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27753. var parsedAnimation = parsedTexture.animations[animationIndex];
  27754. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27755. }
  27756. }
  27757. return texture;
  27758. };
  27759. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27760. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27761. if (noMipmap === void 0) { noMipmap = false; }
  27762. if (invertY === void 0) { invertY = true; }
  27763. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27764. if (onLoad === void 0) { onLoad = null; }
  27765. if (onError === void 0) { onError = null; }
  27766. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27767. if (name.substr(0, 5) !== "data:") {
  27768. name = "data:" + name;
  27769. }
  27770. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27771. };
  27772. // Constants
  27773. Texture.NEAREST_SAMPLINGMODE = 1;
  27774. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27775. Texture.BILINEAR_SAMPLINGMODE = 2;
  27776. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27777. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27778. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27779. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27780. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27781. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27782. Texture.NEAREST_LINEAR = 7;
  27783. Texture.NEAREST_NEAREST = 8;
  27784. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27785. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27786. Texture.LINEAR_LINEAR = 11;
  27787. Texture.LINEAR_NEAREST = 12;
  27788. Texture.EXPLICIT_MODE = 0;
  27789. Texture.SPHERICAL_MODE = 1;
  27790. Texture.PLANAR_MODE = 2;
  27791. Texture.CUBIC_MODE = 3;
  27792. Texture.PROJECTION_MODE = 4;
  27793. Texture.SKYBOX_MODE = 5;
  27794. Texture.INVCUBIC_MODE = 6;
  27795. Texture.EQUIRECTANGULAR_MODE = 7;
  27796. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27797. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27798. Texture.CLAMP_ADDRESSMODE = 0;
  27799. Texture.WRAP_ADDRESSMODE = 1;
  27800. Texture.MIRROR_ADDRESSMODE = 2;
  27801. /**
  27802. * 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
  27803. */
  27804. Texture.UseSerializedUrlIfAny = false;
  27805. __decorate([
  27806. BABYLON.serialize()
  27807. ], Texture.prototype, "url", void 0);
  27808. __decorate([
  27809. BABYLON.serialize()
  27810. ], Texture.prototype, "uOffset", void 0);
  27811. __decorate([
  27812. BABYLON.serialize()
  27813. ], Texture.prototype, "vOffset", void 0);
  27814. __decorate([
  27815. BABYLON.serialize()
  27816. ], Texture.prototype, "uScale", void 0);
  27817. __decorate([
  27818. BABYLON.serialize()
  27819. ], Texture.prototype, "vScale", void 0);
  27820. __decorate([
  27821. BABYLON.serialize()
  27822. ], Texture.prototype, "uAng", void 0);
  27823. __decorate([
  27824. BABYLON.serialize()
  27825. ], Texture.prototype, "vAng", void 0);
  27826. __decorate([
  27827. BABYLON.serialize()
  27828. ], Texture.prototype, "wAng", void 0);
  27829. __decorate([
  27830. BABYLON.serialize()
  27831. ], Texture.prototype, "isBlocking", null);
  27832. return Texture;
  27833. }(BABYLON.BaseTexture));
  27834. BABYLON.Texture = Texture;
  27835. })(BABYLON || (BABYLON = {}));
  27836. //# sourceMappingURL=babylon.texture.js.map
  27837. "use strict";
  27838. var BABYLON;
  27839. (function (BABYLON) {
  27840. var _InstancesBatch = /** @class */ (function () {
  27841. function _InstancesBatch() {
  27842. this.mustReturn = false;
  27843. this.visibleInstances = new Array();
  27844. this.renderSelf = new Array();
  27845. }
  27846. return _InstancesBatch;
  27847. }());
  27848. BABYLON._InstancesBatch = _InstancesBatch;
  27849. var Mesh = /** @class */ (function (_super) {
  27850. __extends(Mesh, _super);
  27851. /**
  27852. * @constructor
  27853. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27854. * @param {Scene} scene The scene to add this mesh to.
  27855. * @param {Node} parent The parent of this mesh, if it has one
  27856. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27857. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27858. * When false, achieved by calling a clone(), also passing False.
  27859. * This will make creation of children, recursive.
  27860. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27861. */
  27862. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27863. if (scene === void 0) { scene = null; }
  27864. if (parent === void 0) { parent = null; }
  27865. if (source === void 0) { source = null; }
  27866. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27867. var _this = _super.call(this, name, scene) || this;
  27868. // Events
  27869. /**
  27870. * An event triggered before rendering the mesh
  27871. * @type {BABYLON.Observable}
  27872. */
  27873. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27874. /**
  27875. * An event triggered after rendering the mesh
  27876. * @type {BABYLON.Observable}
  27877. */
  27878. _this.onAfterRenderObservable = new BABYLON.Observable();
  27879. /**
  27880. * An event triggered before drawing the mesh
  27881. * @type {BABYLON.Observable}
  27882. */
  27883. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27884. // Members
  27885. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27886. _this.instances = new Array();
  27887. _this._LODLevels = new Array();
  27888. _this._visibleInstances = {};
  27889. _this._renderIdForInstances = new Array();
  27890. _this._batchCache = new _InstancesBatch();
  27891. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27892. // Use by builder only to know what orientation were the mesh build in.
  27893. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27894. _this.overrideMaterialSideOrientation = null;
  27895. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27896. // Will be used to save a source mesh reference, If any
  27897. _this._source = null;
  27898. scene = _this.getScene();
  27899. if (source) {
  27900. // Source mesh
  27901. _this._source = source;
  27902. // Geometry
  27903. if (source._geometry) {
  27904. source._geometry.applyToMesh(_this);
  27905. }
  27906. // Deep copy
  27907. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27908. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27909. // Metadata
  27910. if (source.metadata && source.metadata.clone) {
  27911. _this.metadata = source.metadata.clone();
  27912. }
  27913. else {
  27914. _this.metadata = source.metadata;
  27915. }
  27916. // Tags
  27917. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27918. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27919. }
  27920. // Parent
  27921. _this.parent = source.parent;
  27922. // Pivot
  27923. _this.setPivotMatrix(source.getPivotMatrix());
  27924. _this.id = name + "." + source.id;
  27925. // Material
  27926. _this.material = source.material;
  27927. var index;
  27928. if (!doNotCloneChildren) {
  27929. // Children
  27930. var directDescendants = source.getDescendants(true);
  27931. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27932. var child = directDescendants[index_1];
  27933. if (child.clone) {
  27934. child.clone(name + "." + child.name, _this);
  27935. }
  27936. }
  27937. }
  27938. // Physics clone
  27939. var physicsEngine = _this.getScene().getPhysicsEngine();
  27940. if (clonePhysicsImpostor && physicsEngine) {
  27941. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27942. if (impostor) {
  27943. _this.physicsImpostor = impostor.clone(_this);
  27944. }
  27945. }
  27946. // Particles
  27947. for (index = 0; index < scene.particleSystems.length; index++) {
  27948. var system = scene.particleSystems[index];
  27949. if (system.emitter === source) {
  27950. system.clone(system.name, _this);
  27951. }
  27952. }
  27953. _this.computeWorldMatrix(true);
  27954. }
  27955. // Parent
  27956. if (parent !== null) {
  27957. _this.parent = parent;
  27958. }
  27959. return _this;
  27960. }
  27961. Object.defineProperty(Mesh, "FRONTSIDE", {
  27962. /**
  27963. * Mesh side orientation : usually the external or front surface
  27964. */
  27965. get: function () {
  27966. return Mesh._FRONTSIDE;
  27967. },
  27968. enumerable: true,
  27969. configurable: true
  27970. });
  27971. Object.defineProperty(Mesh, "BACKSIDE", {
  27972. /**
  27973. * Mesh side orientation : usually the internal or back surface
  27974. */
  27975. get: function () {
  27976. return Mesh._BACKSIDE;
  27977. },
  27978. enumerable: true,
  27979. configurable: true
  27980. });
  27981. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27982. /**
  27983. * Mesh side orientation : both internal and external or front and back surfaces
  27984. */
  27985. get: function () {
  27986. return Mesh._DOUBLESIDE;
  27987. },
  27988. enumerable: true,
  27989. configurable: true
  27990. });
  27991. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27992. /**
  27993. * Mesh side orientation : by default, `FRONTSIDE`
  27994. */
  27995. get: function () {
  27996. return Mesh._DEFAULTSIDE;
  27997. },
  27998. enumerable: true,
  27999. configurable: true
  28000. });
  28001. Object.defineProperty(Mesh, "NO_CAP", {
  28002. /**
  28003. * Mesh cap setting : no cap
  28004. */
  28005. get: function () {
  28006. return Mesh._NO_CAP;
  28007. },
  28008. enumerable: true,
  28009. configurable: true
  28010. });
  28011. Object.defineProperty(Mesh, "CAP_START", {
  28012. /**
  28013. * Mesh cap setting : one cap at the beginning of the mesh
  28014. */
  28015. get: function () {
  28016. return Mesh._CAP_START;
  28017. },
  28018. enumerable: true,
  28019. configurable: true
  28020. });
  28021. Object.defineProperty(Mesh, "CAP_END", {
  28022. /**
  28023. * Mesh cap setting : one cap at the end of the mesh
  28024. */
  28025. get: function () {
  28026. return Mesh._CAP_END;
  28027. },
  28028. enumerable: true,
  28029. configurable: true
  28030. });
  28031. Object.defineProperty(Mesh, "CAP_ALL", {
  28032. /**
  28033. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  28034. */
  28035. get: function () {
  28036. return Mesh._CAP_ALL;
  28037. },
  28038. enumerable: true,
  28039. configurable: true
  28040. });
  28041. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28042. set: function (callback) {
  28043. if (this._onBeforeDrawObserver) {
  28044. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28045. }
  28046. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28047. },
  28048. enumerable: true,
  28049. configurable: true
  28050. });
  28051. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28052. get: function () {
  28053. return this._morphTargetManager;
  28054. },
  28055. set: function (value) {
  28056. if (this._morphTargetManager === value) {
  28057. return;
  28058. }
  28059. this._morphTargetManager = value;
  28060. this._syncGeometryWithMorphTargetManager();
  28061. },
  28062. enumerable: true,
  28063. configurable: true
  28064. });
  28065. Object.defineProperty(Mesh.prototype, "source", {
  28066. get: function () {
  28067. return this._source;
  28068. },
  28069. enumerable: true,
  28070. configurable: true
  28071. });
  28072. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28073. get: function () {
  28074. return this._unIndexed;
  28075. },
  28076. set: function (value) {
  28077. if (this._unIndexed !== value) {
  28078. this._unIndexed = value;
  28079. this._markSubMeshesAsAttributesDirty();
  28080. }
  28081. },
  28082. enumerable: true,
  28083. configurable: true
  28084. });
  28085. // Methods
  28086. /**
  28087. * Returns the string "Mesh".
  28088. */
  28089. Mesh.prototype.getClassName = function () {
  28090. return "Mesh";
  28091. };
  28092. /**
  28093. * Returns a string.
  28094. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28095. */
  28096. Mesh.prototype.toString = function (fullDetails) {
  28097. var ret = _super.prototype.toString.call(this, fullDetails);
  28098. ret += ", n vertices: " + this.getTotalVertices();
  28099. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28100. if (this.animations) {
  28101. for (var i = 0; i < this.animations.length; i++) {
  28102. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28103. }
  28104. }
  28105. if (fullDetails) {
  28106. if (this._geometry) {
  28107. var ib = this.getIndices();
  28108. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28109. if (vb && ib) {
  28110. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28111. }
  28112. }
  28113. else {
  28114. ret += ", flat shading: UNKNOWN";
  28115. }
  28116. }
  28117. return ret;
  28118. };
  28119. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28120. /**
  28121. * True if the mesh has some Levels Of Details (LOD).
  28122. * Returns a boolean.
  28123. */
  28124. get: function () {
  28125. return this._LODLevels.length > 0;
  28126. },
  28127. enumerable: true,
  28128. configurable: true
  28129. });
  28130. /**
  28131. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28132. * @returns an array of {BABYLON.MeshLODLevel}
  28133. */
  28134. Mesh.prototype.getLODLevels = function () {
  28135. return this._LODLevels;
  28136. };
  28137. Mesh.prototype._sortLODLevels = function () {
  28138. this._LODLevels.sort(function (a, b) {
  28139. if (a.distance < b.distance) {
  28140. return 1;
  28141. }
  28142. if (a.distance > b.distance) {
  28143. return -1;
  28144. }
  28145. return 0;
  28146. });
  28147. };
  28148. /**
  28149. * Add a mesh as LOD level triggered at the given distance.
  28150. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28151. * @param {number} distance The distance from the center of the object to show this level
  28152. * @param {Mesh} mesh The mesh to be added as LOD level
  28153. * @return {Mesh} This mesh (for chaining)
  28154. */
  28155. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28156. if (mesh && mesh._masterMesh) {
  28157. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28158. return this;
  28159. }
  28160. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28161. this._LODLevels.push(level);
  28162. if (mesh) {
  28163. mesh._masterMesh = this;
  28164. }
  28165. this._sortLODLevels();
  28166. return this;
  28167. };
  28168. /**
  28169. * Returns the LOD level mesh at the passed distance or null if not found.
  28170. * It is related to the method `addLODLevel(distance, mesh)`.
  28171. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28172. * Returns an object Mesh or `null`.
  28173. */
  28174. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28175. for (var index = 0; index < this._LODLevels.length; index++) {
  28176. var level = this._LODLevels[index];
  28177. if (level.distance === distance) {
  28178. return level.mesh;
  28179. }
  28180. }
  28181. return null;
  28182. };
  28183. /**
  28184. * Remove a mesh from the LOD array
  28185. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28186. * @param {Mesh} mesh The mesh to be removed.
  28187. * @return {Mesh} This mesh (for chaining)
  28188. */
  28189. Mesh.prototype.removeLODLevel = function (mesh) {
  28190. for (var index = 0; index < this._LODLevels.length; index++) {
  28191. if (this._LODLevels[index].mesh === mesh) {
  28192. this._LODLevels.splice(index, 1);
  28193. if (mesh) {
  28194. mesh._masterMesh = null;
  28195. }
  28196. }
  28197. }
  28198. this._sortLODLevels();
  28199. return this;
  28200. };
  28201. /**
  28202. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28203. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28204. */
  28205. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28206. if (!this._LODLevels || this._LODLevels.length === 0) {
  28207. return this;
  28208. }
  28209. var bSphere;
  28210. if (boundingSphere) {
  28211. bSphere = boundingSphere;
  28212. }
  28213. else {
  28214. var boundingInfo = this.getBoundingInfo();
  28215. bSphere = boundingInfo.boundingSphere;
  28216. }
  28217. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28218. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28219. if (this.onLODLevelSelection) {
  28220. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28221. }
  28222. return this;
  28223. }
  28224. for (var index = 0; index < this._LODLevels.length; index++) {
  28225. var level = this._LODLevels[index];
  28226. if (level.distance < distanceToCamera) {
  28227. if (level.mesh) {
  28228. level.mesh._preActivate();
  28229. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28230. }
  28231. if (this.onLODLevelSelection) {
  28232. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28233. }
  28234. return level.mesh;
  28235. }
  28236. }
  28237. if (this.onLODLevelSelection) {
  28238. this.onLODLevelSelection(distanceToCamera, this, this);
  28239. }
  28240. return this;
  28241. };
  28242. Object.defineProperty(Mesh.prototype, "geometry", {
  28243. /**
  28244. * Returns the mesh internal Geometry object.
  28245. */
  28246. get: function () {
  28247. return this._geometry;
  28248. },
  28249. enumerable: true,
  28250. configurable: true
  28251. });
  28252. /**
  28253. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28254. */
  28255. Mesh.prototype.getTotalVertices = function () {
  28256. if (this._geometry === null || this._geometry === undefined) {
  28257. return 0;
  28258. }
  28259. return this._geometry.getTotalVertices();
  28260. };
  28261. /**
  28262. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28263. * 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.
  28264. * You can force the copy with forceCopy === true
  28265. * Returns null if the mesh has no geometry or no vertex buffer.
  28266. * Possible `kind` values :
  28267. * - BABYLON.VertexBuffer.PositionKind
  28268. * - BABYLON.VertexBuffer.UVKind
  28269. * - BABYLON.VertexBuffer.UV2Kind
  28270. * - BABYLON.VertexBuffer.UV3Kind
  28271. * - BABYLON.VertexBuffer.UV4Kind
  28272. * - BABYLON.VertexBuffer.UV5Kind
  28273. * - BABYLON.VertexBuffer.UV6Kind
  28274. * - BABYLON.VertexBuffer.ColorKind
  28275. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28276. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28277. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28278. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28279. */
  28280. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28281. if (!this._geometry) {
  28282. return null;
  28283. }
  28284. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28285. };
  28286. /**
  28287. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28288. * Returns `null` if the mesh has no geometry.
  28289. * Possible `kind` values :
  28290. * - BABYLON.VertexBuffer.PositionKind
  28291. * - BABYLON.VertexBuffer.UVKind
  28292. * - BABYLON.VertexBuffer.UV2Kind
  28293. * - BABYLON.VertexBuffer.UV3Kind
  28294. * - BABYLON.VertexBuffer.UV4Kind
  28295. * - BABYLON.VertexBuffer.UV5Kind
  28296. * - BABYLON.VertexBuffer.UV6Kind
  28297. * - BABYLON.VertexBuffer.ColorKind
  28298. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28299. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28300. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28301. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28302. */
  28303. Mesh.prototype.getVertexBuffer = function (kind) {
  28304. if (!this._geometry) {
  28305. return null;
  28306. }
  28307. return this._geometry.getVertexBuffer(kind);
  28308. };
  28309. /**
  28310. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28311. * Possible `kind` values :
  28312. * - BABYLON.VertexBuffer.PositionKind
  28313. * - BABYLON.VertexBuffer.UVKind
  28314. * - BABYLON.VertexBuffer.UV2Kind
  28315. * - BABYLON.VertexBuffer.UV3Kind
  28316. * - BABYLON.VertexBuffer.UV4Kind
  28317. * - BABYLON.VertexBuffer.UV5Kind
  28318. * - BABYLON.VertexBuffer.UV6Kind
  28319. * - BABYLON.VertexBuffer.ColorKind
  28320. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28321. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28322. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28323. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28324. */
  28325. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28326. if (!this._geometry) {
  28327. if (this._delayInfo) {
  28328. return this._delayInfo.indexOf(kind) !== -1;
  28329. }
  28330. return false;
  28331. }
  28332. return this._geometry.isVerticesDataPresent(kind);
  28333. };
  28334. /**
  28335. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28336. * Possible `kind` values :
  28337. * - BABYLON.VertexBuffer.PositionKind
  28338. * - BABYLON.VertexBuffer.UVKind
  28339. * - BABYLON.VertexBuffer.UV2Kind
  28340. * - BABYLON.VertexBuffer.UV3Kind
  28341. * - BABYLON.VertexBuffer.UV4Kind
  28342. * - BABYLON.VertexBuffer.UV5Kind
  28343. * - BABYLON.VertexBuffer.UV6Kind
  28344. * - BABYLON.VertexBuffer.ColorKind
  28345. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28346. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28347. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28348. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28349. */
  28350. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28351. if (!this._geometry) {
  28352. if (this._delayInfo) {
  28353. return this._delayInfo.indexOf(kind) !== -1;
  28354. }
  28355. return false;
  28356. }
  28357. return this._geometry.isVertexBufferUpdatable(kind);
  28358. };
  28359. /**
  28360. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28361. * Possible `kind` values :
  28362. * - BABYLON.VertexBuffer.PositionKind
  28363. * - BABYLON.VertexBuffer.UVKind
  28364. * - BABYLON.VertexBuffer.UV2Kind
  28365. * - BABYLON.VertexBuffer.UV3Kind
  28366. * - BABYLON.VertexBuffer.UV4Kind
  28367. * - BABYLON.VertexBuffer.UV5Kind
  28368. * - BABYLON.VertexBuffer.UV6Kind
  28369. * - BABYLON.VertexBuffer.ColorKind
  28370. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28371. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28372. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28373. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28374. */
  28375. Mesh.prototype.getVerticesDataKinds = function () {
  28376. if (!this._geometry) {
  28377. var result = new Array();
  28378. if (this._delayInfo) {
  28379. this._delayInfo.forEach(function (kind, index, array) {
  28380. result.push(kind);
  28381. });
  28382. }
  28383. return result;
  28384. }
  28385. return this._geometry.getVerticesDataKinds();
  28386. };
  28387. /**
  28388. * Returns a positive integer : the total number of indices in this mesh geometry.
  28389. * Returns zero if the mesh has no geometry.
  28390. */
  28391. Mesh.prototype.getTotalIndices = function () {
  28392. if (!this._geometry) {
  28393. return 0;
  28394. }
  28395. return this._geometry.getTotalIndices();
  28396. };
  28397. /**
  28398. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28399. * 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.
  28400. * Returns an empty array if the mesh has no geometry.
  28401. */
  28402. Mesh.prototype.getIndices = function (copyWhenShared) {
  28403. if (!this._geometry) {
  28404. return [];
  28405. }
  28406. return this._geometry.getIndices(copyWhenShared);
  28407. };
  28408. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28409. get: function () {
  28410. return this._masterMesh !== null && this._masterMesh !== undefined;
  28411. },
  28412. enumerable: true,
  28413. configurable: true
  28414. });
  28415. /**
  28416. * Determine if the current mesh is ready to be rendered
  28417. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28418. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28419. * @returns true if all associated assets are ready (material, textures, shaders)
  28420. */
  28421. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28422. if (completeCheck === void 0) { completeCheck = false; }
  28423. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28424. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28425. return false;
  28426. }
  28427. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28428. return false;
  28429. }
  28430. if (!this.subMeshes || this.subMeshes.length === 0) {
  28431. return true;
  28432. }
  28433. if (!completeCheck) {
  28434. return true;
  28435. }
  28436. var engine = this.getEngine();
  28437. var scene = this.getScene();
  28438. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28439. this.computeWorldMatrix();
  28440. var mat = this.material || scene.defaultMaterial;
  28441. if (mat) {
  28442. if (mat.storeEffectOnSubMeshes) {
  28443. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28444. var subMesh = _a[_i];
  28445. var effectiveMaterial = subMesh.getMaterial();
  28446. if (effectiveMaterial) {
  28447. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28448. return false;
  28449. }
  28450. }
  28451. }
  28452. }
  28453. else {
  28454. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28455. return false;
  28456. }
  28457. }
  28458. }
  28459. // Shadows
  28460. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28461. var light = _c[_b];
  28462. var generator = light.getShadowGenerator();
  28463. if (generator) {
  28464. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28465. var subMesh = _e[_d];
  28466. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28467. return false;
  28468. }
  28469. }
  28470. }
  28471. }
  28472. // LOD
  28473. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28474. var lod = _g[_f];
  28475. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28476. return false;
  28477. }
  28478. }
  28479. return true;
  28480. };
  28481. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28482. /**
  28483. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28484. * This property is pertinent only for updatable parametric shapes.
  28485. */
  28486. get: function () {
  28487. return this._areNormalsFrozen;
  28488. },
  28489. enumerable: true,
  28490. configurable: true
  28491. });
  28492. /**
  28493. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28494. * It has no effect at all on other shapes.
  28495. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28496. * Returns the Mesh.
  28497. */
  28498. Mesh.prototype.freezeNormals = function () {
  28499. this._areNormalsFrozen = true;
  28500. return this;
  28501. };
  28502. /**
  28503. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28504. * It has no effect at all on other shapes.
  28505. * It reactivates the mesh normals computation if it was previously frozen.
  28506. * Returns the Mesh.
  28507. */
  28508. Mesh.prototype.unfreezeNormals = function () {
  28509. this._areNormalsFrozen = false;
  28510. return this;
  28511. };
  28512. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28513. /**
  28514. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28515. */
  28516. set: function (count) {
  28517. this._overridenInstanceCount = count;
  28518. },
  28519. enumerable: true,
  28520. configurable: true
  28521. });
  28522. // Methods
  28523. Mesh.prototype._preActivate = function () {
  28524. var sceneRenderId = this.getScene().getRenderId();
  28525. if (this._preActivateId === sceneRenderId) {
  28526. return this;
  28527. }
  28528. this._preActivateId = sceneRenderId;
  28529. this._visibleInstances = null;
  28530. return this;
  28531. };
  28532. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28533. if (this._visibleInstances) {
  28534. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28535. }
  28536. return this;
  28537. };
  28538. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28539. if (!this._visibleInstances) {
  28540. this._visibleInstances = {};
  28541. this._visibleInstances.defaultRenderId = renderId;
  28542. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28543. }
  28544. if (!this._visibleInstances[renderId]) {
  28545. this._visibleInstances[renderId] = new Array();
  28546. }
  28547. this._visibleInstances[renderId].push(instance);
  28548. return this;
  28549. };
  28550. /**
  28551. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28552. * This means the mesh underlying bounding box and sphere are recomputed.
  28553. * Returns the Mesh.
  28554. */
  28555. Mesh.prototype.refreshBoundingInfo = function () {
  28556. return this._refreshBoundingInfo(false);
  28557. };
  28558. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28559. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28560. return this;
  28561. }
  28562. var data = this._getPositionData(applySkeleton);
  28563. if (data) {
  28564. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28565. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28566. }
  28567. if (this.subMeshes) {
  28568. for (var index = 0; index < this.subMeshes.length; index++) {
  28569. this.subMeshes[index].refreshBoundingInfo();
  28570. }
  28571. }
  28572. this._updateBoundingInfo();
  28573. return this;
  28574. };
  28575. Mesh.prototype._getPositionData = function (applySkeleton) {
  28576. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28577. if (data && applySkeleton && this.skeleton) {
  28578. data = BABYLON.Tools.Slice(data);
  28579. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28580. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28581. if (matricesWeightsData && matricesIndicesData) {
  28582. var needExtras = this.numBoneInfluencers > 4;
  28583. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28584. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28585. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28586. var tempVector = BABYLON.Tmp.Vector3[0];
  28587. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28588. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28589. var matWeightIdx = 0;
  28590. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28591. finalMatrix.reset();
  28592. var inf;
  28593. var weight;
  28594. for (inf = 0; inf < 4; inf++) {
  28595. weight = matricesWeightsData[matWeightIdx + inf];
  28596. if (weight <= 0)
  28597. break;
  28598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28599. finalMatrix.addToSelf(tempMatrix);
  28600. }
  28601. if (needExtras) {
  28602. for (inf = 0; inf < 4; inf++) {
  28603. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28604. if (weight <= 0)
  28605. break;
  28606. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28607. finalMatrix.addToSelf(tempMatrix);
  28608. }
  28609. }
  28610. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28611. tempVector.toArray(data, index);
  28612. }
  28613. }
  28614. }
  28615. return data;
  28616. };
  28617. Mesh.prototype._createGlobalSubMesh = function (force) {
  28618. var totalVertices = this.getTotalVertices();
  28619. if (!totalVertices || !this.getIndices()) {
  28620. return null;
  28621. }
  28622. // Check if we need to recreate the submeshes
  28623. if (this.subMeshes && this.subMeshes.length > 0) {
  28624. var ib = this.getIndices();
  28625. if (!ib) {
  28626. return null;
  28627. }
  28628. var totalIndices = ib.length;
  28629. var needToRecreate = false;
  28630. if (force) {
  28631. needToRecreate = true;
  28632. }
  28633. else {
  28634. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28635. var submesh = _a[_i];
  28636. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28637. needToRecreate = true;
  28638. break;
  28639. }
  28640. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28641. needToRecreate = true;
  28642. break;
  28643. }
  28644. }
  28645. }
  28646. if (!needToRecreate) {
  28647. return this.subMeshes[0];
  28648. }
  28649. }
  28650. this.releaseSubMeshes();
  28651. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28652. };
  28653. Mesh.prototype.subdivide = function (count) {
  28654. if (count < 1) {
  28655. return;
  28656. }
  28657. var totalIndices = this.getTotalIndices();
  28658. var subdivisionSize = (totalIndices / count) | 0;
  28659. var offset = 0;
  28660. // Ensure that subdivisionSize is a multiple of 3
  28661. while (subdivisionSize % 3 !== 0) {
  28662. subdivisionSize++;
  28663. }
  28664. this.releaseSubMeshes();
  28665. for (var index = 0; index < count; index++) {
  28666. if (offset >= totalIndices) {
  28667. break;
  28668. }
  28669. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28670. offset += subdivisionSize;
  28671. }
  28672. this.synchronizeInstances();
  28673. };
  28674. /**
  28675. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28676. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28677. * The `data` are either a numeric array either a Float32Array.
  28678. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28679. * 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).
  28680. * Note that a new underlying VertexBuffer object is created each call.
  28681. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28682. *
  28683. * Possible `kind` values :
  28684. * - BABYLON.VertexBuffer.PositionKind
  28685. * - BABYLON.VertexBuffer.UVKind
  28686. * - BABYLON.VertexBuffer.UV2Kind
  28687. * - BABYLON.VertexBuffer.UV3Kind
  28688. * - BABYLON.VertexBuffer.UV4Kind
  28689. * - BABYLON.VertexBuffer.UV5Kind
  28690. * - BABYLON.VertexBuffer.UV6Kind
  28691. * - BABYLON.VertexBuffer.ColorKind
  28692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28696. *
  28697. * Returns the Mesh.
  28698. */
  28699. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28700. if (updatable === void 0) { updatable = false; }
  28701. if (!this._geometry) {
  28702. var vertexData = new BABYLON.VertexData();
  28703. vertexData.set(data, kind);
  28704. var scene = this.getScene();
  28705. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28706. }
  28707. else {
  28708. this._geometry.setVerticesData(kind, data, updatable, stride);
  28709. }
  28710. return this;
  28711. };
  28712. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28713. if (updatable === void 0) { updatable = true; }
  28714. var vb = this.getVertexBuffer(kind);
  28715. if (!vb || vb.isUpdatable() === updatable) {
  28716. return;
  28717. }
  28718. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28719. };
  28720. /**
  28721. * Sets the mesh VertexBuffer.
  28722. * Returns the Mesh.
  28723. */
  28724. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28725. if (!this._geometry) {
  28726. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28727. }
  28728. this._geometry.setVerticesBuffer(buffer);
  28729. return this;
  28730. };
  28731. /**
  28732. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28733. * If the mesh has no geometry, it is simply returned as it is.
  28734. * The `data` are either a numeric array either a Float32Array.
  28735. * No new underlying VertexBuffer object is created.
  28736. * 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.
  28737. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28738. *
  28739. * Possible `kind` values :
  28740. * - BABYLON.VertexBuffer.PositionKind
  28741. * - BABYLON.VertexBuffer.UVKind
  28742. * - BABYLON.VertexBuffer.UV2Kind
  28743. * - BABYLON.VertexBuffer.UV3Kind
  28744. * - BABYLON.VertexBuffer.UV4Kind
  28745. * - BABYLON.VertexBuffer.UV5Kind
  28746. * - BABYLON.VertexBuffer.UV6Kind
  28747. * - BABYLON.VertexBuffer.ColorKind
  28748. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28749. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28750. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28751. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28752. *
  28753. * Returns the Mesh.
  28754. */
  28755. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28756. if (!this._geometry) {
  28757. return this;
  28758. }
  28759. if (!makeItUnique) {
  28760. this._geometry.updateVerticesData(kind, data, updateExtends);
  28761. }
  28762. else {
  28763. this.makeGeometryUnique();
  28764. this.updateVerticesData(kind, data, updateExtends, false);
  28765. }
  28766. return this;
  28767. };
  28768. /**
  28769. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28770. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28771. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28772. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28773. * Returns the Mesh.
  28774. */
  28775. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28776. if (computeNormals === void 0) { computeNormals = true; }
  28777. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28778. if (!positions) {
  28779. return this;
  28780. }
  28781. positionFunction(positions);
  28782. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28783. if (computeNormals) {
  28784. var indices = this.getIndices();
  28785. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28786. if (!normals) {
  28787. return this;
  28788. }
  28789. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28790. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28791. }
  28792. return this;
  28793. };
  28794. /**
  28795. * Creates a un-shared specific occurence of the geometry for the mesh.
  28796. * Returns the Mesh.
  28797. */
  28798. Mesh.prototype.makeGeometryUnique = function () {
  28799. if (!this._geometry) {
  28800. return this;
  28801. }
  28802. var oldGeometry = this._geometry;
  28803. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28804. oldGeometry.releaseForMesh(this, true);
  28805. geometry.applyToMesh(this);
  28806. return this;
  28807. };
  28808. /**
  28809. * Sets the mesh indices.
  28810. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28811. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28812. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28813. * This method creates a new index buffer each call.
  28814. * Returns the Mesh.
  28815. */
  28816. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28817. if (totalVertices === void 0) { totalVertices = null; }
  28818. if (updatable === void 0) { updatable = false; }
  28819. if (!this._geometry) {
  28820. var vertexData = new BABYLON.VertexData();
  28821. vertexData.indices = indices;
  28822. var scene = this.getScene();
  28823. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28824. }
  28825. else {
  28826. this._geometry.setIndices(indices, totalVertices, updatable);
  28827. }
  28828. return this;
  28829. };
  28830. /**
  28831. * Update the current index buffer
  28832. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28833. * Returns the Mesh.
  28834. */
  28835. Mesh.prototype.updateIndices = function (indices, offset) {
  28836. if (!this._geometry) {
  28837. return this;
  28838. }
  28839. this._geometry.updateIndices(indices, offset);
  28840. return this;
  28841. };
  28842. /**
  28843. * Invert the geometry to move from a right handed system to a left handed one.
  28844. * Returns the Mesh.
  28845. */
  28846. Mesh.prototype.toLeftHanded = function () {
  28847. if (!this._geometry) {
  28848. return this;
  28849. }
  28850. this._geometry.toLeftHanded();
  28851. return this;
  28852. };
  28853. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28854. if (!this._geometry) {
  28855. return this;
  28856. }
  28857. var engine = this.getScene().getEngine();
  28858. // Wireframe
  28859. var indexToBind;
  28860. if (this._unIndexed) {
  28861. indexToBind = null;
  28862. }
  28863. else {
  28864. switch (fillMode) {
  28865. case BABYLON.Material.PointFillMode:
  28866. indexToBind = null;
  28867. break;
  28868. case BABYLON.Material.WireFrameFillMode:
  28869. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28870. break;
  28871. default:
  28872. case BABYLON.Material.TriangleFillMode:
  28873. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28874. break;
  28875. }
  28876. }
  28877. // VBOs
  28878. this._geometry._bind(effect, indexToBind);
  28879. return this;
  28880. };
  28881. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28882. if (alternate === void 0) { alternate = false; }
  28883. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28884. return this;
  28885. }
  28886. this.onBeforeDrawObservable.notifyObservers(this);
  28887. var scene = this.getScene();
  28888. var engine = scene.getEngine();
  28889. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28890. // or triangles as points
  28891. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28892. }
  28893. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28894. // Triangles as wireframe
  28895. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28896. }
  28897. else {
  28898. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28899. }
  28900. if (scene._isAlternateRenderingEnabled && !alternate) {
  28901. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28902. if (!effect || !scene.activeCamera) {
  28903. return this;
  28904. }
  28905. scene._switchToAlternateCameraConfiguration(true);
  28906. this._effectiveMaterial.bindView(effect);
  28907. this._effectiveMaterial.bindViewProjection(effect);
  28908. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28909. this._draw(subMesh, fillMode, instancesCount, true);
  28910. engine.setViewport(scene.activeCamera.viewport);
  28911. scene._switchToAlternateCameraConfiguration(false);
  28912. this._effectiveMaterial.bindView(effect);
  28913. this._effectiveMaterial.bindViewProjection(effect);
  28914. }
  28915. return this;
  28916. };
  28917. /**
  28918. * Registers for this mesh a javascript function called just before the rendering process.
  28919. * This function is passed the current mesh.
  28920. * Return the Mesh.
  28921. */
  28922. Mesh.prototype.registerBeforeRender = function (func) {
  28923. this.onBeforeRenderObservable.add(func);
  28924. return this;
  28925. };
  28926. /**
  28927. * Disposes a previously registered javascript function called before the rendering.
  28928. * This function is passed the current mesh.
  28929. * Returns the Mesh.
  28930. */
  28931. Mesh.prototype.unregisterBeforeRender = function (func) {
  28932. this.onBeforeRenderObservable.removeCallback(func);
  28933. return this;
  28934. };
  28935. /**
  28936. * Registers for this mesh a javascript function called just after the rendering is complete.
  28937. * This function is passed the current mesh.
  28938. * Returns the Mesh.
  28939. */
  28940. Mesh.prototype.registerAfterRender = function (func) {
  28941. this.onAfterRenderObservable.add(func);
  28942. return this;
  28943. };
  28944. /**
  28945. * Disposes a previously registered javascript function called after the rendering.
  28946. * This function is passed the current mesh.
  28947. * Return the Mesh.
  28948. */
  28949. Mesh.prototype.unregisterAfterRender = function (func) {
  28950. this.onAfterRenderObservable.removeCallback(func);
  28951. return this;
  28952. };
  28953. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28954. var scene = this.getScene();
  28955. this._batchCache.mustReturn = false;
  28956. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28957. this._batchCache.visibleInstances[subMeshId] = null;
  28958. if (this._visibleInstances) {
  28959. var currentRenderId = scene.getRenderId();
  28960. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28961. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28962. var selfRenderId = this._renderId;
  28963. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28964. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28965. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28966. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28967. }
  28968. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28969. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28970. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28971. this._batchCache.mustReturn = true;
  28972. return this._batchCache;
  28973. }
  28974. if (currentRenderId !== selfRenderId) {
  28975. this._batchCache.renderSelf[subMeshId] = false;
  28976. }
  28977. }
  28978. this._renderIdForInstances[subMeshId] = currentRenderId;
  28979. }
  28980. return this._batchCache;
  28981. };
  28982. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28983. var visibleInstances = batch.visibleInstances[subMesh._id];
  28984. if (!visibleInstances) {
  28985. return this;
  28986. }
  28987. var matricesCount = visibleInstances.length + 1;
  28988. var bufferSize = matricesCount * 16 * 4;
  28989. var currentInstancesBufferSize = this._instancesBufferSize;
  28990. var instancesBuffer = this._instancesBuffer;
  28991. while (this._instancesBufferSize < bufferSize) {
  28992. this._instancesBufferSize *= 2;
  28993. }
  28994. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28995. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28996. }
  28997. var offset = 0;
  28998. var instancesCount = 0;
  28999. var world = this.getWorldMatrix();
  29000. if (batch.renderSelf[subMesh._id]) {
  29001. world.copyToArray(this._instancesData, offset);
  29002. offset += 16;
  29003. instancesCount++;
  29004. }
  29005. if (visibleInstances) {
  29006. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  29007. var instance = visibleInstances[instanceIndex];
  29008. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  29009. offset += 16;
  29010. instancesCount++;
  29011. }
  29012. }
  29013. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  29014. if (instancesBuffer) {
  29015. instancesBuffer.dispose();
  29016. }
  29017. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  29018. this._instancesBuffer = instancesBuffer;
  29019. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  29020. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  29021. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  29022. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  29023. }
  29024. else {
  29025. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  29026. }
  29027. this._bind(subMesh, effect, fillMode);
  29028. this._draw(subMesh, fillMode, instancesCount);
  29029. engine.unbindInstanceAttributes();
  29030. return this;
  29031. };
  29032. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  29033. var scene = this.getScene();
  29034. var engine = scene.getEngine();
  29035. if (hardwareInstancedRendering) {
  29036. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  29037. }
  29038. else {
  29039. if (batch.renderSelf[subMesh._id]) {
  29040. // Draw
  29041. if (onBeforeDraw) {
  29042. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29043. }
  29044. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29045. }
  29046. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29047. if (visibleInstancesForSubMesh) {
  29048. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29049. var instance = visibleInstancesForSubMesh[instanceIndex];
  29050. // World
  29051. var world = instance.getWorldMatrix();
  29052. if (onBeforeDraw) {
  29053. onBeforeDraw(true, world, effectiveMaterial);
  29054. }
  29055. // Draw
  29056. this._draw(subMesh, fillMode);
  29057. }
  29058. }
  29059. }
  29060. return this;
  29061. };
  29062. /**
  29063. * Triggers the draw call for the mesh.
  29064. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29065. * Returns the Mesh.
  29066. */
  29067. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29068. this.checkOcclusionQuery();
  29069. if (this._isOccluded) {
  29070. return this;
  29071. }
  29072. var scene = this.getScene();
  29073. // Managing instances
  29074. var batch = this._getInstancesRenderList(subMesh._id);
  29075. if (batch.mustReturn) {
  29076. return this;
  29077. }
  29078. // Checking geometry state
  29079. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29080. return this;
  29081. }
  29082. this.onBeforeRenderObservable.notifyObservers(this);
  29083. var engine = scene.getEngine();
  29084. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29085. // Material
  29086. var material = subMesh.getMaterial();
  29087. if (!material) {
  29088. return this;
  29089. }
  29090. this._effectiveMaterial = material;
  29091. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29092. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29093. return this;
  29094. }
  29095. }
  29096. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29097. return this;
  29098. }
  29099. // Alpha mode
  29100. if (enableAlphaMode) {
  29101. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29102. }
  29103. // Outline - step 1
  29104. var savedDepthWrite = engine.getDepthWrite();
  29105. if (this.renderOutline) {
  29106. engine.setDepthWrite(false);
  29107. scene.getOutlineRenderer().render(subMesh, batch);
  29108. engine.setDepthWrite(savedDepthWrite);
  29109. }
  29110. var effect;
  29111. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29112. effect = subMesh.effect;
  29113. }
  29114. else {
  29115. effect = this._effectiveMaterial.getEffect();
  29116. }
  29117. if (!effect) {
  29118. return this;
  29119. }
  29120. var sideOrientation = this.overrideMaterialSideOrientation;
  29121. if (sideOrientation == null) {
  29122. sideOrientation = this._effectiveMaterial.sideOrientation;
  29123. if (this._getWorldMatrixDeterminant() < 0) {
  29124. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29125. }
  29126. }
  29127. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29128. if (this._effectiveMaterial.forceDepthWrite) {
  29129. engine.setDepthWrite(true);
  29130. }
  29131. // Bind
  29132. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29133. if (!hardwareInstancedRendering) {
  29134. this._bind(subMesh, effect, fillMode);
  29135. }
  29136. var world = this.getWorldMatrix();
  29137. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29138. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29139. }
  29140. else {
  29141. this._effectiveMaterial.bind(world, this);
  29142. }
  29143. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29144. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29145. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29146. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29147. }
  29148. // Draw
  29149. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29150. // Unbind
  29151. this._effectiveMaterial.unbind();
  29152. // Outline - step 2
  29153. if (this.renderOutline && savedDepthWrite) {
  29154. engine.setDepthWrite(true);
  29155. engine.setColorWrite(false);
  29156. scene.getOutlineRenderer().render(subMesh, batch);
  29157. engine.setColorWrite(true);
  29158. }
  29159. // Overlay
  29160. if (this.renderOverlay) {
  29161. var currentMode = engine.getAlphaMode();
  29162. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29163. scene.getOutlineRenderer().render(subMesh, batch, true);
  29164. engine.setAlphaMode(currentMode);
  29165. }
  29166. this.onAfterRenderObservable.notifyObservers(this);
  29167. return this;
  29168. };
  29169. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29170. if (isInstance && effectiveMaterial) {
  29171. effectiveMaterial.bindOnlyWorldMatrix(world);
  29172. }
  29173. };
  29174. /**
  29175. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29176. */
  29177. Mesh.prototype.getEmittedParticleSystems = function () {
  29178. var results = new Array();
  29179. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29180. var particleSystem = this.getScene().particleSystems[index];
  29181. if (particleSystem.emitter === this) {
  29182. results.push(particleSystem);
  29183. }
  29184. }
  29185. return results;
  29186. };
  29187. /**
  29188. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29189. */
  29190. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29191. var results = new Array();
  29192. var descendants = this.getDescendants();
  29193. descendants.push(this);
  29194. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29195. var particleSystem = this.getScene().particleSystems[index];
  29196. var emitter = particleSystem.emitter;
  29197. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29198. results.push(particleSystem);
  29199. }
  29200. }
  29201. return results;
  29202. };
  29203. Mesh.prototype._checkDelayState = function () {
  29204. var scene = this.getScene();
  29205. if (this._geometry) {
  29206. this._geometry.load(scene);
  29207. }
  29208. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29209. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29210. this._queueLoad(scene);
  29211. }
  29212. return this;
  29213. };
  29214. Mesh.prototype._queueLoad = function (scene) {
  29215. var _this = this;
  29216. scene._addPendingData(this);
  29217. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29218. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29219. if (data instanceof ArrayBuffer) {
  29220. _this._delayLoadingFunction(data, _this);
  29221. }
  29222. else {
  29223. _this._delayLoadingFunction(JSON.parse(data), _this);
  29224. }
  29225. _this.instances.forEach(function (instance) {
  29226. instance._syncSubMeshes();
  29227. });
  29228. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29229. scene._removePendingData(_this);
  29230. }, function () { }, scene.database, getBinaryData);
  29231. return this;
  29232. };
  29233. /**
  29234. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29235. */
  29236. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29237. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29238. return false;
  29239. }
  29240. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29241. return false;
  29242. }
  29243. this._checkDelayState();
  29244. return true;
  29245. };
  29246. /**
  29247. * Sets the mesh material by the material or multiMaterial `id` property.
  29248. * The material `id` is a string identifying the material or the multiMaterial.
  29249. * This method returns the Mesh.
  29250. */
  29251. Mesh.prototype.setMaterialByID = function (id) {
  29252. var materials = this.getScene().materials;
  29253. var index;
  29254. for (index = materials.length - 1; index > -1; index--) {
  29255. if (materials[index].id === id) {
  29256. this.material = materials[index];
  29257. return this;
  29258. }
  29259. }
  29260. // Multi
  29261. var multiMaterials = this.getScene().multiMaterials;
  29262. for (index = multiMaterials.length - 1; index > -1; index--) {
  29263. if (multiMaterials[index].id === id) {
  29264. this.material = multiMaterials[index];
  29265. return this;
  29266. }
  29267. }
  29268. return this;
  29269. };
  29270. /**
  29271. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29272. */
  29273. Mesh.prototype.getAnimatables = function () {
  29274. var results = new Array();
  29275. if (this.material) {
  29276. results.push(this.material);
  29277. }
  29278. if (this.skeleton) {
  29279. results.push(this.skeleton);
  29280. }
  29281. return results;
  29282. };
  29283. /**
  29284. * Modifies the mesh geometry according to the passed transformation matrix.
  29285. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29286. * The mesh normals are modified accordingly the same transformation.
  29287. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29288. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29289. * Returns the Mesh.
  29290. */
  29291. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29292. // Position
  29293. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29294. return this;
  29295. }
  29296. var submeshes = this.subMeshes.splice(0);
  29297. this._resetPointsArrayCache();
  29298. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29299. var temp = new Array();
  29300. var index;
  29301. for (index = 0; index < data.length; index += 3) {
  29302. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29303. }
  29304. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29305. // Normals
  29306. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29307. return this;
  29308. }
  29309. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29310. temp = [];
  29311. for (index = 0; index < data.length; index += 3) {
  29312. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29313. }
  29314. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29315. // flip faces?
  29316. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29317. this.flipFaces();
  29318. }
  29319. // Restore submeshes
  29320. this.releaseSubMeshes();
  29321. this.subMeshes = submeshes;
  29322. return this;
  29323. };
  29324. /**
  29325. * Modifies the mesh geometry according to its own current World Matrix.
  29326. * The mesh World Matrix is then reset.
  29327. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29328. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29329. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29330. * Returns the Mesh.
  29331. */
  29332. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29333. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29334. this.scaling.copyFromFloats(1, 1, 1);
  29335. this.position.copyFromFloats(0, 0, 0);
  29336. this.rotation.copyFromFloats(0, 0, 0);
  29337. //only if quaternion is already set
  29338. if (this.rotationQuaternion) {
  29339. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29340. }
  29341. this._worldMatrix = BABYLON.Matrix.Identity();
  29342. return this;
  29343. };
  29344. Object.defineProperty(Mesh.prototype, "_positions", {
  29345. // Cache
  29346. get: function () {
  29347. if (this._geometry) {
  29348. return this._geometry._positions;
  29349. }
  29350. return null;
  29351. },
  29352. enumerable: true,
  29353. configurable: true
  29354. });
  29355. Mesh.prototype._resetPointsArrayCache = function () {
  29356. if (this._geometry) {
  29357. this._geometry._resetPointsArrayCache();
  29358. }
  29359. return this;
  29360. };
  29361. Mesh.prototype._generatePointsArray = function () {
  29362. if (this._geometry) {
  29363. return this._geometry._generatePointsArray();
  29364. }
  29365. return false;
  29366. };
  29367. /**
  29368. * Returns a new Mesh object generated from the current mesh properties.
  29369. * This method must not get confused with createInstance().
  29370. * The parameter `name` is a string, the name given to the new mesh.
  29371. * The optional parameter `newParent` can be any Node object (default `null`).
  29372. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29373. * 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.
  29374. */
  29375. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29376. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29377. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29378. };
  29379. /**
  29380. * Releases resources associated with this mesh.
  29381. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29382. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29383. */
  29384. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29385. var _this = this;
  29386. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29387. this.morphTargetManager = null;
  29388. if (this._geometry) {
  29389. this._geometry.releaseForMesh(this, true);
  29390. }
  29391. // Sources
  29392. var meshes = this.getScene().meshes;
  29393. meshes.forEach(function (abstractMesh) {
  29394. var mesh = abstractMesh;
  29395. if (mesh._source && mesh._source === _this) {
  29396. mesh._source = null;
  29397. }
  29398. });
  29399. this._source = null;
  29400. // Instances
  29401. if (this._instancesBuffer) {
  29402. this._instancesBuffer.dispose();
  29403. this._instancesBuffer = null;
  29404. }
  29405. while (this.instances.length) {
  29406. this.instances[0].dispose();
  29407. }
  29408. // Effect layers.
  29409. var effectLayers = this.getScene().effectLayers;
  29410. for (var i = 0; i < effectLayers.length; i++) {
  29411. var effectLayer = effectLayers[i];
  29412. if (effectLayer) {
  29413. effectLayer._disposeMesh(this);
  29414. }
  29415. }
  29416. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29417. };
  29418. /**
  29419. * Modifies the mesh geometry according to a displacement map.
  29420. * 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.
  29421. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29422. * This method returns nothing.
  29423. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29424. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29425. * 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.
  29426. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29427. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29428. *
  29429. * Returns the Mesh.
  29430. */
  29431. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29432. var _this = this;
  29433. var scene = this.getScene();
  29434. var onload = function (img) {
  29435. // Getting height map data
  29436. var canvas = document.createElement("canvas");
  29437. var context = canvas.getContext("2d");
  29438. var heightMapWidth = img.width;
  29439. var heightMapHeight = img.height;
  29440. canvas.width = heightMapWidth;
  29441. canvas.height = heightMapHeight;
  29442. context.drawImage(img, 0, 0);
  29443. // Create VertexData from map data
  29444. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29445. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29446. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29447. //execute success callback, if set
  29448. if (onSuccess) {
  29449. onSuccess(_this);
  29450. }
  29451. };
  29452. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29453. return this;
  29454. };
  29455. /**
  29456. * Modifies the mesh geometry according to a displacementMap buffer.
  29457. * 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.
  29458. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29459. * This method returns nothing.
  29460. * 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.
  29461. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29462. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29463. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29464. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29465. *
  29466. * Returns the Mesh.
  29467. */
  29468. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29469. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29470. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29471. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29472. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29473. return this;
  29474. }
  29475. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29476. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29477. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29478. var position = BABYLON.Vector3.Zero();
  29479. var normal = BABYLON.Vector3.Zero();
  29480. var uv = BABYLON.Vector2.Zero();
  29481. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29482. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29483. for (var index = 0; index < positions.length; index += 3) {
  29484. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29485. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29486. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29487. // Compute height
  29488. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29489. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29490. var pos = (u + v * heightMapWidth) * 4;
  29491. var r = buffer[pos] / 255.0;
  29492. var g = buffer[pos + 1] / 255.0;
  29493. var b = buffer[pos + 2] / 255.0;
  29494. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29495. normal.normalize();
  29496. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29497. position = position.add(normal);
  29498. position.toArray(positions, index);
  29499. }
  29500. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29501. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29502. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29503. return this;
  29504. };
  29505. /**
  29506. * Modify the mesh to get a flat shading rendering.
  29507. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29508. * This method returns the Mesh.
  29509. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29510. */
  29511. Mesh.prototype.convertToFlatShadedMesh = function () {
  29512. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29513. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29514. var kinds = this.getVerticesDataKinds();
  29515. var vbs = {};
  29516. var data = {};
  29517. var newdata = {};
  29518. var updatableNormals = false;
  29519. var kindIndex;
  29520. var kind;
  29521. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29522. kind = kinds[kindIndex];
  29523. var vertexBuffer = this.getVertexBuffer(kind);
  29524. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29525. updatableNormals = vertexBuffer.isUpdatable();
  29526. kinds.splice(kindIndex, 1);
  29527. kindIndex--;
  29528. continue;
  29529. }
  29530. vbs[kind] = vertexBuffer;
  29531. data[kind] = vbs[kind].getData();
  29532. newdata[kind] = [];
  29533. }
  29534. // Save previous submeshes
  29535. var previousSubmeshes = this.subMeshes.slice(0);
  29536. var indices = this.getIndices();
  29537. var totalIndices = this.getTotalIndices();
  29538. // Generating unique vertices per face
  29539. var index;
  29540. for (index = 0; index < totalIndices; index++) {
  29541. var vertexIndex = indices[index];
  29542. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29543. kind = kinds[kindIndex];
  29544. var stride = vbs[kind].getStrideSize();
  29545. for (var offset = 0; offset < stride; offset++) {
  29546. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29547. }
  29548. }
  29549. }
  29550. // Updating faces & normal
  29551. var normals = [];
  29552. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29553. for (index = 0; index < totalIndices; index += 3) {
  29554. indices[index] = index;
  29555. indices[index + 1] = index + 1;
  29556. indices[index + 2] = index + 2;
  29557. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29558. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29559. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29560. var p1p2 = p1.subtract(p2);
  29561. var p3p2 = p3.subtract(p2);
  29562. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29563. // Store same normals for every vertex
  29564. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29565. normals.push(normal.x);
  29566. normals.push(normal.y);
  29567. normals.push(normal.z);
  29568. }
  29569. }
  29570. this.setIndices(indices);
  29571. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29572. // Updating vertex buffers
  29573. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29574. kind = kinds[kindIndex];
  29575. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29576. }
  29577. // Updating submeshes
  29578. this.releaseSubMeshes();
  29579. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29580. var previousOne = previousSubmeshes[submeshIndex];
  29581. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29582. }
  29583. this.synchronizeInstances();
  29584. return this;
  29585. };
  29586. /**
  29587. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29588. * In other words, more vertices, no more indices and a single bigger VBO.
  29589. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29590. * Returns the Mesh.
  29591. */
  29592. Mesh.prototype.convertToUnIndexedMesh = function () {
  29593. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29594. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29595. var kinds = this.getVerticesDataKinds();
  29596. var vbs = {};
  29597. var data = {};
  29598. var newdata = {};
  29599. var kindIndex;
  29600. var kind;
  29601. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29602. kind = kinds[kindIndex];
  29603. var vertexBuffer = this.getVertexBuffer(kind);
  29604. vbs[kind] = vertexBuffer;
  29605. data[kind] = vbs[kind].getData();
  29606. newdata[kind] = [];
  29607. }
  29608. // Save previous submeshes
  29609. var previousSubmeshes = this.subMeshes.slice(0);
  29610. var indices = this.getIndices();
  29611. var totalIndices = this.getTotalIndices();
  29612. // Generating unique vertices per face
  29613. var index;
  29614. for (index = 0; index < totalIndices; index++) {
  29615. var vertexIndex = indices[index];
  29616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29617. kind = kinds[kindIndex];
  29618. var stride = vbs[kind].getStrideSize();
  29619. for (var offset = 0; offset < stride; offset++) {
  29620. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29621. }
  29622. }
  29623. }
  29624. // Updating indices
  29625. for (index = 0; index < totalIndices; index += 3) {
  29626. indices[index] = index;
  29627. indices[index + 1] = index + 1;
  29628. indices[index + 2] = index + 2;
  29629. }
  29630. this.setIndices(indices);
  29631. // Updating vertex buffers
  29632. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29633. kind = kinds[kindIndex];
  29634. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29635. }
  29636. // Updating submeshes
  29637. this.releaseSubMeshes();
  29638. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29639. var previousOne = previousSubmeshes[submeshIndex];
  29640. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29641. }
  29642. this._unIndexed = true;
  29643. this.synchronizeInstances();
  29644. return this;
  29645. };
  29646. /**
  29647. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29648. * This method returns the Mesh.
  29649. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29650. */
  29651. Mesh.prototype.flipFaces = function (flipNormals) {
  29652. if (flipNormals === void 0) { flipNormals = false; }
  29653. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29654. var i;
  29655. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29656. for (i = 0; i < vertex_data.normals.length; i++) {
  29657. vertex_data.normals[i] *= -1;
  29658. }
  29659. }
  29660. if (vertex_data.indices) {
  29661. var temp;
  29662. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29663. // reassign indices
  29664. temp = vertex_data.indices[i + 1];
  29665. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29666. vertex_data.indices[i + 2] = temp;
  29667. }
  29668. }
  29669. vertex_data.applyToMesh(this);
  29670. return this;
  29671. };
  29672. // Instances
  29673. /**
  29674. * Creates a new InstancedMesh object from the mesh model.
  29675. * An instance shares the same properties and the same material than its model.
  29676. * Only these properties of each instance can then be set individually :
  29677. * - position
  29678. * - rotation
  29679. * - rotationQuaternion
  29680. * - setPivotMatrix
  29681. * - scaling
  29682. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29683. * Warning : this method is not supported for Line mesh and LineSystem
  29684. */
  29685. Mesh.prototype.createInstance = function (name) {
  29686. return new BABYLON.InstancedMesh(name, this);
  29687. };
  29688. /**
  29689. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29690. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29691. * This method returns the Mesh.
  29692. */
  29693. Mesh.prototype.synchronizeInstances = function () {
  29694. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29695. var instance = this.instances[instanceIndex];
  29696. instance._syncSubMeshes();
  29697. }
  29698. return this;
  29699. };
  29700. /**
  29701. * Simplify the mesh according to the given array of settings.
  29702. * Function will return immediately and will simplify async. It returns the Mesh.
  29703. * @param settings a collection of simplification settings.
  29704. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29705. * @param type the type of simplification to run.
  29706. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29707. */
  29708. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29709. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29710. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29711. this.getScene().simplificationQueue.addTask({
  29712. settings: settings,
  29713. parallelProcessing: parallelProcessing,
  29714. mesh: this,
  29715. simplificationType: simplificationType,
  29716. successCallback: successCallback
  29717. });
  29718. return this;
  29719. };
  29720. /**
  29721. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29722. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29723. * This should be used together with the simplification to avoid disappearing triangles.
  29724. * Returns the Mesh.
  29725. * @param successCallback an optional success callback to be called after the optimization finished.
  29726. */
  29727. Mesh.prototype.optimizeIndices = function (successCallback) {
  29728. var _this = this;
  29729. var indices = this.getIndices();
  29730. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29731. if (!positions || !indices) {
  29732. return this;
  29733. }
  29734. var vectorPositions = new Array();
  29735. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29736. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29737. }
  29738. var dupes = new Array();
  29739. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29740. var realPos = vectorPositions.length - 1 - iteration;
  29741. var testedPosition = vectorPositions[realPos];
  29742. for (var j = 0; j < realPos; ++j) {
  29743. var againstPosition = vectorPositions[j];
  29744. if (testedPosition.equals(againstPosition)) {
  29745. dupes[realPos] = j;
  29746. break;
  29747. }
  29748. }
  29749. }, function () {
  29750. for (var i = 0; i < indices.length; ++i) {
  29751. indices[i] = dupes[indices[i]] || indices[i];
  29752. }
  29753. //indices are now reordered
  29754. var originalSubMeshes = _this.subMeshes.slice(0);
  29755. _this.setIndices(indices);
  29756. _this.subMeshes = originalSubMeshes;
  29757. if (successCallback) {
  29758. successCallback(_this);
  29759. }
  29760. });
  29761. return this;
  29762. };
  29763. Mesh.prototype.serialize = function (serializationObject) {
  29764. serializationObject.name = this.name;
  29765. serializationObject.id = this.id;
  29766. serializationObject.type = this.getClassName();
  29767. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29768. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29769. }
  29770. serializationObject.position = this.position.asArray();
  29771. if (this.rotationQuaternion) {
  29772. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29773. }
  29774. else if (this.rotation) {
  29775. serializationObject.rotation = this.rotation.asArray();
  29776. }
  29777. serializationObject.scaling = this.scaling.asArray();
  29778. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29779. serializationObject.isEnabled = this.isEnabled(false);
  29780. serializationObject.isVisible = this.isVisible;
  29781. serializationObject.infiniteDistance = this.infiniteDistance;
  29782. serializationObject.pickable = this.isPickable;
  29783. serializationObject.receiveShadows = this.receiveShadows;
  29784. serializationObject.billboardMode = this.billboardMode;
  29785. serializationObject.visibility = this.visibility;
  29786. serializationObject.checkCollisions = this.checkCollisions;
  29787. serializationObject.isBlocker = this.isBlocker;
  29788. // Parent
  29789. if (this.parent) {
  29790. serializationObject.parentId = this.parent.id;
  29791. }
  29792. // Geometry
  29793. serializationObject.isUnIndexed = this.isUnIndexed;
  29794. var geometry = this._geometry;
  29795. if (geometry) {
  29796. var geometryId = geometry.id;
  29797. serializationObject.geometryId = geometryId;
  29798. // SubMeshes
  29799. serializationObject.subMeshes = [];
  29800. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29801. var subMesh = this.subMeshes[subIndex];
  29802. serializationObject.subMeshes.push({
  29803. materialIndex: subMesh.materialIndex,
  29804. verticesStart: subMesh.verticesStart,
  29805. verticesCount: subMesh.verticesCount,
  29806. indexStart: subMesh.indexStart,
  29807. indexCount: subMesh.indexCount
  29808. });
  29809. }
  29810. }
  29811. // Material
  29812. if (this.material) {
  29813. serializationObject.materialId = this.material.id;
  29814. }
  29815. else {
  29816. this.material = null;
  29817. }
  29818. // Morph targets
  29819. if (this.morphTargetManager) {
  29820. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29821. }
  29822. // Skeleton
  29823. if (this.skeleton) {
  29824. serializationObject.skeletonId = this.skeleton.id;
  29825. }
  29826. // Physics
  29827. //TODO implement correct serialization for physics impostors.
  29828. var impostor = this.getPhysicsImpostor();
  29829. if (impostor) {
  29830. serializationObject.physicsMass = impostor.getParam("mass");
  29831. serializationObject.physicsFriction = impostor.getParam("friction");
  29832. serializationObject.physicsRestitution = impostor.getParam("mass");
  29833. serializationObject.physicsImpostor = impostor.type;
  29834. }
  29835. // Metadata
  29836. if (this.metadata) {
  29837. serializationObject.metadata = this.metadata;
  29838. }
  29839. // Instances
  29840. serializationObject.instances = [];
  29841. for (var index = 0; index < this.instances.length; index++) {
  29842. var instance = this.instances[index];
  29843. var serializationInstance = {
  29844. name: instance.name,
  29845. id: instance.id,
  29846. position: instance.position.asArray(),
  29847. scaling: instance.scaling.asArray()
  29848. };
  29849. if (instance.rotationQuaternion) {
  29850. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29851. }
  29852. else if (instance.rotation) {
  29853. serializationInstance.rotation = instance.rotation.asArray();
  29854. }
  29855. serializationObject.instances.push(serializationInstance);
  29856. // Animations
  29857. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29858. serializationInstance.ranges = instance.serializeAnimationRanges();
  29859. }
  29860. //
  29861. // Animations
  29862. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29863. serializationObject.ranges = this.serializeAnimationRanges();
  29864. // Layer mask
  29865. serializationObject.layerMask = this.layerMask;
  29866. // Alpha
  29867. serializationObject.alphaIndex = this.alphaIndex;
  29868. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29869. // Overlay
  29870. serializationObject.overlayAlpha = this.overlayAlpha;
  29871. serializationObject.overlayColor = this.overlayColor.asArray();
  29872. serializationObject.renderOverlay = this.renderOverlay;
  29873. // Fog
  29874. serializationObject.applyFog = this.applyFog;
  29875. // Action Manager
  29876. if (this.actionManager) {
  29877. serializationObject.actions = this.actionManager.serialize(this.name);
  29878. }
  29879. };
  29880. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29881. if (!this.geometry) {
  29882. return;
  29883. }
  29884. this._markSubMeshesAsAttributesDirty();
  29885. var morphTargetManager = this._morphTargetManager;
  29886. if (morphTargetManager && morphTargetManager.vertexCount) {
  29887. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29888. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29889. this.morphTargetManager = null;
  29890. return;
  29891. }
  29892. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29893. var morphTarget = morphTargetManager.getActiveTarget(index);
  29894. var positions = morphTarget.getPositions();
  29895. if (!positions) {
  29896. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29897. return;
  29898. }
  29899. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29900. var normals = morphTarget.getNormals();
  29901. if (normals) {
  29902. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29903. }
  29904. var tangents = morphTarget.getTangents();
  29905. if (tangents) {
  29906. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29907. }
  29908. }
  29909. }
  29910. else {
  29911. var index = 0;
  29912. // Positions
  29913. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29914. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29915. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29916. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29917. }
  29918. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29919. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29920. }
  29921. index++;
  29922. }
  29923. }
  29924. };
  29925. // Statics
  29926. /**
  29927. * Returns a new Mesh object parsed from the source provided.
  29928. * The parameter `parsedMesh` is the source.
  29929. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29930. */
  29931. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29932. var mesh;
  29933. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29934. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29935. }
  29936. else {
  29937. mesh = new Mesh(parsedMesh.name, scene);
  29938. }
  29939. mesh.id = parsedMesh.id;
  29940. if (BABYLON.Tags) {
  29941. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29942. }
  29943. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29944. if (parsedMesh.metadata !== undefined) {
  29945. mesh.metadata = parsedMesh.metadata;
  29946. }
  29947. if (parsedMesh.rotationQuaternion) {
  29948. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29949. }
  29950. else if (parsedMesh.rotation) {
  29951. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29952. }
  29953. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29954. if (parsedMesh.localMatrix) {
  29955. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29956. }
  29957. else if (parsedMesh.pivotMatrix) {
  29958. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29959. }
  29960. mesh.setEnabled(parsedMesh.isEnabled);
  29961. mesh.isVisible = parsedMesh.isVisible;
  29962. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29963. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29964. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29965. if (parsedMesh.applyFog !== undefined) {
  29966. mesh.applyFog = parsedMesh.applyFog;
  29967. }
  29968. if (parsedMesh.pickable !== undefined) {
  29969. mesh.isPickable = parsedMesh.pickable;
  29970. }
  29971. if (parsedMesh.alphaIndex !== undefined) {
  29972. mesh.alphaIndex = parsedMesh.alphaIndex;
  29973. }
  29974. mesh.receiveShadows = parsedMesh.receiveShadows;
  29975. mesh.billboardMode = parsedMesh.billboardMode;
  29976. if (parsedMesh.visibility !== undefined) {
  29977. mesh.visibility = parsedMesh.visibility;
  29978. }
  29979. mesh.checkCollisions = parsedMesh.checkCollisions;
  29980. if (parsedMesh.isBlocker !== undefined) {
  29981. mesh.isBlocker = parsedMesh.isBlocker;
  29982. }
  29983. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29984. // freezeWorldMatrix
  29985. if (parsedMesh.freezeWorldMatrix) {
  29986. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29987. }
  29988. // Parent
  29989. if (parsedMesh.parentId) {
  29990. mesh._waitingParentId = parsedMesh.parentId;
  29991. }
  29992. // Actions
  29993. if (parsedMesh.actions !== undefined) {
  29994. mesh._waitingActions = parsedMesh.actions;
  29995. }
  29996. // Overlay
  29997. if (parsedMesh.overlayAlpha !== undefined) {
  29998. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29999. }
  30000. if (parsedMesh.overlayColor !== undefined) {
  30001. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  30002. }
  30003. if (parsedMesh.renderOverlay !== undefined) {
  30004. mesh.renderOverlay = parsedMesh.renderOverlay;
  30005. }
  30006. // Geometry
  30007. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  30008. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  30009. if (parsedMesh.delayLoadingFile) {
  30010. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30011. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  30012. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  30013. if (parsedMesh._binaryInfo) {
  30014. mesh._binaryInfo = parsedMesh._binaryInfo;
  30015. }
  30016. mesh._delayInfo = [];
  30017. if (parsedMesh.hasUVs) {
  30018. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30019. }
  30020. if (parsedMesh.hasUVs2) {
  30021. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30022. }
  30023. if (parsedMesh.hasUVs3) {
  30024. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30025. }
  30026. if (parsedMesh.hasUVs4) {
  30027. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30028. }
  30029. if (parsedMesh.hasUVs5) {
  30030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30031. }
  30032. if (parsedMesh.hasUVs6) {
  30033. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30034. }
  30035. if (parsedMesh.hasColors) {
  30036. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30037. }
  30038. if (parsedMesh.hasMatricesIndices) {
  30039. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30040. }
  30041. if (parsedMesh.hasMatricesWeights) {
  30042. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30043. }
  30044. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30045. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30046. mesh._checkDelayState();
  30047. }
  30048. }
  30049. else {
  30050. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30051. }
  30052. // Material
  30053. if (parsedMesh.materialId) {
  30054. mesh.setMaterialByID(parsedMesh.materialId);
  30055. }
  30056. else {
  30057. mesh.material = null;
  30058. }
  30059. // Morph targets
  30060. if (parsedMesh.morphTargetManagerId > -1) {
  30061. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30062. }
  30063. // Skeleton
  30064. if (parsedMesh.skeletonId > -1) {
  30065. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30066. if (parsedMesh.numBoneInfluencers) {
  30067. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30068. }
  30069. }
  30070. // Animations
  30071. if (parsedMesh.animations) {
  30072. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30073. var parsedAnimation = parsedMesh.animations[animationIndex];
  30074. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30075. }
  30076. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30077. }
  30078. if (parsedMesh.autoAnimate) {
  30079. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30080. }
  30081. // Layer Mask
  30082. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30083. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30084. }
  30085. else {
  30086. mesh.layerMask = 0x0FFFFFFF;
  30087. }
  30088. // Physics
  30089. if (parsedMesh.physicsImpostor) {
  30090. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30091. mass: parsedMesh.physicsMass,
  30092. friction: parsedMesh.physicsFriction,
  30093. restitution: parsedMesh.physicsRestitution
  30094. }, scene);
  30095. }
  30096. // Instances
  30097. if (parsedMesh.instances) {
  30098. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30099. var parsedInstance = parsedMesh.instances[index];
  30100. var instance = mesh.createInstance(parsedInstance.name);
  30101. if (parsedInstance.id) {
  30102. instance.id = parsedInstance.id;
  30103. }
  30104. if (BABYLON.Tags) {
  30105. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30106. }
  30107. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30108. if (parsedInstance.parentId) {
  30109. instance._waitingParentId = parsedInstance.parentId;
  30110. }
  30111. if (parsedInstance.rotationQuaternion) {
  30112. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30113. }
  30114. else if (parsedInstance.rotation) {
  30115. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30116. }
  30117. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30118. instance.checkCollisions = mesh.checkCollisions;
  30119. if (parsedMesh.animations) {
  30120. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30121. parsedAnimation = parsedMesh.animations[animationIndex];
  30122. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30123. }
  30124. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30125. }
  30126. }
  30127. }
  30128. return mesh;
  30129. };
  30130. /**
  30131. * Creates a ribbon mesh.
  30132. * Please consider using the same method from the MeshBuilder class instead.
  30133. * 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.
  30134. *
  30135. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30136. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30137. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30138. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30139. * 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.
  30140. * 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.
  30141. * 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
  30142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30143. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30145. */
  30146. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30147. if (closeArray === void 0) { closeArray = false; }
  30148. if (updatable === void 0) { updatable = false; }
  30149. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30150. pathArray: pathArray,
  30151. closeArray: closeArray,
  30152. closePath: closePath,
  30153. offset: offset,
  30154. updatable: updatable,
  30155. sideOrientation: sideOrientation,
  30156. instance: instance
  30157. }, scene);
  30158. };
  30159. /**
  30160. * Creates a plane polygonal mesh. By default, this is a disc.
  30161. * Please consider using the same method from the MeshBuilder class instead.
  30162. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30163. * 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.
  30164. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30165. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30167. */
  30168. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30169. if (scene === void 0) { scene = null; }
  30170. var options = {
  30171. radius: radius,
  30172. tessellation: tessellation,
  30173. sideOrientation: sideOrientation,
  30174. updatable: updatable
  30175. };
  30176. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30177. };
  30178. /**
  30179. * Creates a box mesh.
  30180. * Please consider using the same method from the MeshBuilder class instead.
  30181. * The parameter `size` sets the size (float) of each box side (default 1).
  30182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30185. */
  30186. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30187. if (scene === void 0) { scene = null; }
  30188. var options = {
  30189. size: size,
  30190. sideOrientation: sideOrientation,
  30191. updatable: updatable
  30192. };
  30193. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30194. };
  30195. /**
  30196. * Creates a sphere mesh.
  30197. * Please consider using the same method from the MeshBuilder class instead.
  30198. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30199. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30200. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30201. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30203. */
  30204. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30205. var options = {
  30206. segments: segments,
  30207. diameterX: diameter,
  30208. diameterY: diameter,
  30209. diameterZ: diameter,
  30210. sideOrientation: sideOrientation,
  30211. updatable: updatable
  30212. };
  30213. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30214. };
  30215. /**
  30216. * Creates a cylinder or a cone mesh.
  30217. * Please consider using the same method from the MeshBuilder class instead.
  30218. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30219. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30220. * 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.
  30221. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30222. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30223. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30224. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30226. */
  30227. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30228. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30229. if (scene !== undefined) {
  30230. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30231. updatable = scene;
  30232. }
  30233. scene = subdivisions;
  30234. subdivisions = 1;
  30235. }
  30236. var options = {
  30237. height: height,
  30238. diameterTop: diameterTop,
  30239. diameterBottom: diameterBottom,
  30240. tessellation: tessellation,
  30241. subdivisions: subdivisions,
  30242. sideOrientation: sideOrientation,
  30243. updatable: updatable
  30244. };
  30245. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30246. };
  30247. // Torus (Code from SharpDX.org)
  30248. /**
  30249. * Creates a torus mesh.
  30250. * Please consider using the same method from the MeshBuilder class instead.
  30251. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30252. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30253. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30255. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30257. */
  30258. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30259. var options = {
  30260. diameter: diameter,
  30261. thickness: thickness,
  30262. tessellation: tessellation,
  30263. sideOrientation: sideOrientation,
  30264. updatable: updatable
  30265. };
  30266. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30267. };
  30268. /**
  30269. * Creates a torus knot mesh.
  30270. * Please consider using the same method from the MeshBuilder class instead.
  30271. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30272. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30273. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30274. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30276. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30278. */
  30279. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30280. var options = {
  30281. radius: radius,
  30282. tube: tube,
  30283. radialSegments: radialSegments,
  30284. tubularSegments: tubularSegments,
  30285. p: p,
  30286. q: q,
  30287. sideOrientation: sideOrientation,
  30288. updatable: updatable
  30289. };
  30290. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30291. };
  30292. /**
  30293. * Creates a line mesh.
  30294. * Please consider using the same method from the MeshBuilder class instead.
  30295. * 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.
  30296. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30297. * The parameter `points` is an array successive Vector3.
  30298. * 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
  30299. * When updating an instance, remember that only point positions can change, not the number of points.
  30300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30301. */
  30302. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30303. if (scene === void 0) { scene = null; }
  30304. if (updatable === void 0) { updatable = false; }
  30305. if (instance === void 0) { instance = null; }
  30306. var options = {
  30307. points: points,
  30308. updatable: updatable,
  30309. instance: instance
  30310. };
  30311. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30312. };
  30313. /**
  30314. * Creates a dashed line mesh.
  30315. * Please consider using the same method from the MeshBuilder class instead.
  30316. * 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.
  30317. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30318. * The parameter `points` is an array successive Vector3.
  30319. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30320. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30321. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30322. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  30323. * When updating an instance, remember that only point positions can change, not the number of points.
  30324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30325. */
  30326. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30327. if (scene === void 0) { scene = null; }
  30328. var options = {
  30329. points: points,
  30330. dashSize: dashSize,
  30331. gapSize: gapSize,
  30332. dashNb: dashNb,
  30333. updatable: updatable,
  30334. instance: instance
  30335. };
  30336. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30337. };
  30338. /**
  30339. * Creates a polygon mesh.
  30340. * Please consider using the same method from the MeshBuilder class instead.
  30341. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30342. * 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.
  30343. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30345. * Remember you can only change the shape positions, not their number when updating a polygon.
  30346. */
  30347. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30348. var options = {
  30349. shape: shape,
  30350. holes: holes,
  30351. updatable: updatable,
  30352. sideOrientation: sideOrientation
  30353. };
  30354. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30355. };
  30356. /**
  30357. * Creates an extruded polygon mesh, with depth in the Y direction.
  30358. * Please consider using the same method from the MeshBuilder class instead.
  30359. */
  30360. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30361. var options = {
  30362. shape: shape,
  30363. holes: holes,
  30364. depth: depth,
  30365. updatable: updatable,
  30366. sideOrientation: sideOrientation
  30367. };
  30368. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30369. };
  30370. /**
  30371. * Creates an extruded shape mesh.
  30372. * 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.
  30373. * Please consider using the same method from the MeshBuilder class instead.
  30374. *
  30375. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30376. * 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
  30377. * extruded along the Z axis.
  30378. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30379. * 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.
  30380. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30381. * 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
  30382. * 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
  30383. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30384. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30385. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30387. */
  30388. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30389. if (scene === void 0) { scene = null; }
  30390. var options = {
  30391. shape: shape,
  30392. path: path,
  30393. scale: scale,
  30394. rotation: rotation,
  30395. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30396. sideOrientation: sideOrientation,
  30397. instance: instance,
  30398. updatable: updatable
  30399. };
  30400. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30401. };
  30402. /**
  30403. * Creates an custom extruded shape mesh.
  30404. * 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.
  30405. * Please consider using the same method from the MeshBuilder class instead.
  30406. *
  30407. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30408. * 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
  30409. * extruded along the Z axis.
  30410. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30411. * 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
  30412. * and the distance of this point from the begining of the path :
  30413. * ```javascript
  30414. * var rotationFunction = function(i, distance) {
  30415. * // do things
  30416. * return rotationValue; }
  30417. * ```
  30418. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30419. * 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
  30420. * and the distance of this point from the begining of the path :
  30421. * ```javascript
  30422. * var scaleFunction = function(i, distance) {
  30423. * // do things
  30424. * return scaleValue;}
  30425. * ```
  30426. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30427. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30428. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30429. * 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
  30430. * 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
  30431. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30435. */
  30436. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30437. var options = {
  30438. shape: shape,
  30439. path: path,
  30440. scaleFunction: scaleFunction,
  30441. rotationFunction: rotationFunction,
  30442. ribbonCloseArray: ribbonCloseArray,
  30443. ribbonClosePath: ribbonClosePath,
  30444. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30445. sideOrientation: sideOrientation,
  30446. instance: instance,
  30447. updatable: updatable
  30448. };
  30449. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30450. };
  30451. /**
  30452. * Creates lathe mesh.
  30453. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30454. * Please consider using the same method from the MeshBuilder class instead.
  30455. * 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
  30456. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30457. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30458. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30462. */
  30463. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30464. var options = {
  30465. shape: shape,
  30466. radius: radius,
  30467. tessellation: tessellation,
  30468. sideOrientation: sideOrientation,
  30469. updatable: updatable
  30470. };
  30471. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30472. };
  30473. /**
  30474. * Creates a plane mesh.
  30475. * Please consider using the same method from the MeshBuilder class instead.
  30476. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30478. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30480. */
  30481. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30482. var options = {
  30483. size: size,
  30484. width: size,
  30485. height: size,
  30486. sideOrientation: sideOrientation,
  30487. updatable: updatable
  30488. };
  30489. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30490. };
  30491. /**
  30492. * Creates a ground mesh.
  30493. * Please consider using the same method from the MeshBuilder class instead.
  30494. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30495. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30497. */
  30498. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30499. var options = {
  30500. width: width,
  30501. height: height,
  30502. subdivisions: subdivisions,
  30503. updatable: updatable
  30504. };
  30505. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30506. };
  30507. /**
  30508. * Creates a tiled ground mesh.
  30509. * Please consider using the same method from the MeshBuilder class instead.
  30510. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30511. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30512. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30513. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30514. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30515. * numbers of subdivisions on the ground width and height of each tile.
  30516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30517. */
  30518. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30519. var options = {
  30520. xmin: xmin,
  30521. zmin: zmin,
  30522. xmax: xmax,
  30523. zmax: zmax,
  30524. subdivisions: subdivisions,
  30525. precision: precision,
  30526. updatable: updatable
  30527. };
  30528. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30529. };
  30530. /**
  30531. * Creates a ground mesh from a height map.
  30532. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30533. * Please consider using the same method from the MeshBuilder class instead.
  30534. * The parameter `url` sets the URL of the height map image resource.
  30535. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30536. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30537. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30538. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30539. * 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).
  30540. * This function is passed the newly built mesh :
  30541. * ```javascript
  30542. * function(mesh) { // do things
  30543. * return; }
  30544. * ```
  30545. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30546. */
  30547. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30548. var options = {
  30549. width: width,
  30550. height: height,
  30551. subdivisions: subdivisions,
  30552. minHeight: minHeight,
  30553. maxHeight: maxHeight,
  30554. updatable: updatable,
  30555. onReady: onReady
  30556. };
  30557. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30558. };
  30559. /**
  30560. * Creates a tube mesh.
  30561. * 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.
  30562. * Please consider using the same method from the MeshBuilder class instead.
  30563. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30564. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30565. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30566. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30567. * 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.
  30568. * It must return a radius value (positive float) :
  30569. * ```javascript
  30570. * var radiusFunction = function(i, distance) {
  30571. * // do things
  30572. * return radius; }
  30573. * ```
  30574. * 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
  30575. * 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
  30576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30579. */
  30580. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30581. var options = {
  30582. path: path,
  30583. radius: radius,
  30584. tessellation: tessellation,
  30585. radiusFunction: radiusFunction,
  30586. arc: 1,
  30587. cap: cap,
  30588. updatable: updatable,
  30589. sideOrientation: sideOrientation,
  30590. instance: instance
  30591. };
  30592. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30593. };
  30594. /**
  30595. * Creates a polyhedron mesh.
  30596. * Please consider using the same method from the MeshBuilder class instead.
  30597. * 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
  30598. * to choose the wanted type.
  30599. * The parameter `size` (positive float, default 1) sets the polygon size.
  30600. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30601. * 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`.
  30602. * 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
  30603. * 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)`).
  30604. * 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
  30605. * 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.
  30606. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30607. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30609. */
  30610. Mesh.CreatePolyhedron = function (name, options, scene) {
  30611. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30612. };
  30613. /**
  30614. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30615. * Please consider using the same method from the MeshBuilder class instead.
  30616. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30617. * 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`).
  30618. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30619. * 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.
  30620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30623. */
  30624. Mesh.CreateIcoSphere = function (name, options, scene) {
  30625. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30626. };
  30627. /**
  30628. * Creates a decal mesh.
  30629. * Please consider using the same method from the MeshBuilder class instead.
  30630. * 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.
  30631. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30632. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30633. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30634. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30635. */
  30636. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30637. var options = {
  30638. position: position,
  30639. normal: normal,
  30640. size: size,
  30641. angle: angle
  30642. };
  30643. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30644. };
  30645. // Skeletons
  30646. /**
  30647. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30648. */
  30649. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30650. if (!this._sourcePositions) {
  30651. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30652. if (!source) {
  30653. return this._sourcePositions;
  30654. }
  30655. this._sourcePositions = new Float32Array(source);
  30656. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30657. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30658. }
  30659. }
  30660. return this._sourcePositions;
  30661. };
  30662. /**
  30663. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30664. */
  30665. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30666. if (!this._sourceNormals) {
  30667. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30668. if (!source) {
  30669. return this._sourceNormals;
  30670. }
  30671. this._sourceNormals = new Float32Array(source);
  30672. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30673. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30674. }
  30675. }
  30676. return this._sourceNormals;
  30677. };
  30678. /**
  30679. * Updates the vertex buffer by applying transformation from the bones.
  30680. * Returns the Mesh.
  30681. *
  30682. * @param {skeleton} skeleton to apply
  30683. */
  30684. Mesh.prototype.applySkeleton = function (skeleton) {
  30685. if (!this.geometry) {
  30686. return this;
  30687. }
  30688. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30689. return this;
  30690. }
  30691. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30692. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30693. return this;
  30694. }
  30695. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30696. return this;
  30697. }
  30698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30699. return this;
  30700. }
  30701. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30702. return this;
  30703. }
  30704. if (!this._sourcePositions) {
  30705. var submeshes = this.subMeshes.slice();
  30706. this.setPositionsForCPUSkinning();
  30707. this.subMeshes = submeshes;
  30708. }
  30709. if (!this._sourceNormals) {
  30710. this.setNormalsForCPUSkinning();
  30711. }
  30712. // positionsData checks for not being Float32Array will only pass at most once
  30713. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30714. if (!positionsData) {
  30715. return this;
  30716. }
  30717. if (!(positionsData instanceof Float32Array)) {
  30718. positionsData = new Float32Array(positionsData);
  30719. }
  30720. // normalsData checks for not being Float32Array will only pass at most once
  30721. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30722. if (!normalsData) {
  30723. return this;
  30724. }
  30725. if (!(normalsData instanceof Float32Array)) {
  30726. normalsData = new Float32Array(normalsData);
  30727. }
  30728. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30729. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30730. if (!matricesWeightsData || !matricesIndicesData) {
  30731. return this;
  30732. }
  30733. var needExtras = this.numBoneInfluencers > 4;
  30734. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30735. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30736. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30737. var tempVector3 = BABYLON.Vector3.Zero();
  30738. var finalMatrix = new BABYLON.Matrix();
  30739. var tempMatrix = new BABYLON.Matrix();
  30740. var matWeightIdx = 0;
  30741. var inf;
  30742. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30743. var weight;
  30744. for (inf = 0; inf < 4; inf++) {
  30745. weight = matricesWeightsData[matWeightIdx + inf];
  30746. if (weight > 0) {
  30747. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30748. finalMatrix.addToSelf(tempMatrix);
  30749. }
  30750. else
  30751. break;
  30752. }
  30753. if (needExtras) {
  30754. for (inf = 0; inf < 4; inf++) {
  30755. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30756. if (weight > 0) {
  30757. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30758. finalMatrix.addToSelf(tempMatrix);
  30759. }
  30760. else
  30761. break;
  30762. }
  30763. }
  30764. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30765. tempVector3.toArray(positionsData, index);
  30766. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30767. tempVector3.toArray(normalsData, index);
  30768. finalMatrix.reset();
  30769. }
  30770. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30771. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30772. return this;
  30773. };
  30774. // Tools
  30775. /**
  30776. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30777. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30778. */
  30779. Mesh.MinMax = function (meshes) {
  30780. var minVector = null;
  30781. var maxVector = null;
  30782. meshes.forEach(function (mesh, index, array) {
  30783. var boundingInfo = mesh.getBoundingInfo();
  30784. var boundingBox = boundingInfo.boundingBox;
  30785. if (!minVector || !maxVector) {
  30786. minVector = boundingBox.minimumWorld;
  30787. maxVector = boundingBox.maximumWorld;
  30788. }
  30789. else {
  30790. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30791. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30792. }
  30793. });
  30794. if (!minVector || !maxVector) {
  30795. return {
  30796. min: BABYLON.Vector3.Zero(),
  30797. max: BABYLON.Vector3.Zero()
  30798. };
  30799. }
  30800. return {
  30801. min: minVector,
  30802. max: maxVector
  30803. };
  30804. };
  30805. /**
  30806. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30807. */
  30808. Mesh.Center = function (meshesOrMinMaxVector) {
  30809. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30810. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30811. };
  30812. /**
  30813. * Merge the array of meshes into a single mesh for performance reasons.
  30814. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30815. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30816. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30817. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30818. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30819. */
  30820. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30821. if (disposeSource === void 0) { disposeSource = true; }
  30822. var index;
  30823. if (!allow32BitsIndices) {
  30824. var totalVertices = 0;
  30825. // Counting vertices
  30826. for (index = 0; index < meshes.length; index++) {
  30827. if (meshes[index]) {
  30828. totalVertices += meshes[index].getTotalVertices();
  30829. if (totalVertices > 65536) {
  30830. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30831. return null;
  30832. }
  30833. }
  30834. }
  30835. }
  30836. // Merge
  30837. var vertexData = null;
  30838. var otherVertexData;
  30839. var indiceArray = new Array();
  30840. var source = null;
  30841. for (index = 0; index < meshes.length; index++) {
  30842. if (meshes[index]) {
  30843. meshes[index].computeWorldMatrix(true);
  30844. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30845. otherVertexData.transform(meshes[index].getWorldMatrix());
  30846. if (vertexData) {
  30847. vertexData.merge(otherVertexData);
  30848. }
  30849. else {
  30850. vertexData = otherVertexData;
  30851. source = meshes[index];
  30852. }
  30853. if (subdivideWithSubMeshes) {
  30854. indiceArray.push(meshes[index].getTotalIndices());
  30855. }
  30856. }
  30857. }
  30858. source = source;
  30859. if (!meshSubclass) {
  30860. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30861. }
  30862. vertexData.applyToMesh(meshSubclass);
  30863. // Setting properties
  30864. meshSubclass.material = source.material;
  30865. meshSubclass.checkCollisions = source.checkCollisions;
  30866. // Cleaning
  30867. if (disposeSource) {
  30868. for (index = 0; index < meshes.length; index++) {
  30869. if (meshes[index]) {
  30870. meshes[index].dispose();
  30871. }
  30872. }
  30873. }
  30874. // Subdivide
  30875. if (subdivideWithSubMeshes) {
  30876. //-- Suppresions du submesh global
  30877. meshSubclass.releaseSubMeshes();
  30878. index = 0;
  30879. var offset = 0;
  30880. //-- aplique la subdivision en fonction du tableau d'indices
  30881. while (index < indiceArray.length) {
  30882. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30883. offset += indiceArray[index];
  30884. index++;
  30885. }
  30886. }
  30887. return meshSubclass;
  30888. };
  30889. // Consts
  30890. Mesh._FRONTSIDE = 0;
  30891. Mesh._BACKSIDE = 1;
  30892. Mesh._DOUBLESIDE = 2;
  30893. Mesh._DEFAULTSIDE = 0;
  30894. Mesh._NO_CAP = 0;
  30895. Mesh._CAP_START = 1;
  30896. Mesh._CAP_END = 2;
  30897. Mesh._CAP_ALL = 3;
  30898. return Mesh;
  30899. }(BABYLON.AbstractMesh));
  30900. BABYLON.Mesh = Mesh;
  30901. })(BABYLON || (BABYLON = {}));
  30902. //# sourceMappingURL=babylon.mesh.js.map
  30903. "use strict";
  30904. var BABYLON;
  30905. (function (BABYLON) {
  30906. var BaseSubMesh = /** @class */ (function () {
  30907. function BaseSubMesh() {
  30908. }
  30909. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30910. get: function () {
  30911. return this._materialEffect;
  30912. },
  30913. enumerable: true,
  30914. configurable: true
  30915. });
  30916. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30917. if (defines === void 0) { defines = null; }
  30918. if (this._materialEffect === effect) {
  30919. if (!effect) {
  30920. this._materialDefines = null;
  30921. }
  30922. return;
  30923. }
  30924. this._materialDefines = defines;
  30925. this._materialEffect = effect;
  30926. };
  30927. return BaseSubMesh;
  30928. }());
  30929. BABYLON.BaseSubMesh = BaseSubMesh;
  30930. var SubMesh = /** @class */ (function (_super) {
  30931. __extends(SubMesh, _super);
  30932. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30933. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30934. var _this = _super.call(this) || this;
  30935. _this.materialIndex = materialIndex;
  30936. _this.verticesStart = verticesStart;
  30937. _this.verticesCount = verticesCount;
  30938. _this.indexStart = indexStart;
  30939. _this.indexCount = indexCount;
  30940. _this._renderId = 0;
  30941. _this._mesh = mesh;
  30942. _this._renderingMesh = renderingMesh || mesh;
  30943. mesh.subMeshes.push(_this);
  30944. _this._trianglePlanes = [];
  30945. _this._id = mesh.subMeshes.length - 1;
  30946. if (createBoundingBox) {
  30947. _this.refreshBoundingInfo();
  30948. mesh.computeWorldMatrix(true);
  30949. }
  30950. return _this;
  30951. }
  30952. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30953. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30954. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30955. };
  30956. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30957. get: function () {
  30958. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. /**
  30964. * Returns the submesh BoudingInfo object.
  30965. */
  30966. SubMesh.prototype.getBoundingInfo = function () {
  30967. if (this.IsGlobal) {
  30968. return this._mesh.getBoundingInfo();
  30969. }
  30970. return this._boundingInfo;
  30971. };
  30972. /**
  30973. * Sets the submesh BoundingInfo.
  30974. * Return the SubMesh.
  30975. */
  30976. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30977. this._boundingInfo = boundingInfo;
  30978. return this;
  30979. };
  30980. /**
  30981. * Returns the mesh of the current submesh.
  30982. */
  30983. SubMesh.prototype.getMesh = function () {
  30984. return this._mesh;
  30985. };
  30986. /**
  30987. * Returns the rendering mesh of the submesh.
  30988. */
  30989. SubMesh.prototype.getRenderingMesh = function () {
  30990. return this._renderingMesh;
  30991. };
  30992. /**
  30993. * Returns the submesh material.
  30994. */
  30995. SubMesh.prototype.getMaterial = function () {
  30996. var rootMaterial = this._renderingMesh.material;
  30997. if (rootMaterial === null || rootMaterial === undefined) {
  30998. return this._mesh.getScene().defaultMaterial;
  30999. }
  31000. else if (rootMaterial.getSubMaterial) {
  31001. var multiMaterial = rootMaterial;
  31002. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  31003. if (this._currentMaterial !== effectiveMaterial) {
  31004. this._currentMaterial = effectiveMaterial;
  31005. this._materialDefines = null;
  31006. }
  31007. return effectiveMaterial;
  31008. }
  31009. return rootMaterial;
  31010. };
  31011. // Methods
  31012. /**
  31013. * Sets a new updated BoundingInfo object to the submesh.
  31014. * Returns the SubMesh.
  31015. */
  31016. SubMesh.prototype.refreshBoundingInfo = function () {
  31017. this._lastColliderWorldVertices = null;
  31018. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  31019. return this;
  31020. }
  31021. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31022. if (!data) {
  31023. this._boundingInfo = this._mesh.getBoundingInfo();
  31024. return this;
  31025. }
  31026. var indices = this._renderingMesh.getIndices();
  31027. var extend;
  31028. //is this the only submesh?
  31029. if (this.indexStart === 0 && this.indexCount === indices.length) {
  31030. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31031. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  31032. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  31033. }
  31034. else {
  31035. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  31036. }
  31037. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31038. return this;
  31039. };
  31040. SubMesh.prototype._checkCollision = function (collider) {
  31041. var boundingInfo = this.getBoundingInfo();
  31042. return boundingInfo._checkCollision(collider);
  31043. };
  31044. /**
  31045. * Updates the submesh BoundingInfo.
  31046. * Returns the Submesh.
  31047. */
  31048. SubMesh.prototype.updateBoundingInfo = function (world) {
  31049. var boundingInfo = this.getBoundingInfo();
  31050. if (!boundingInfo) {
  31051. this.refreshBoundingInfo();
  31052. boundingInfo = this.getBoundingInfo();
  31053. }
  31054. boundingInfo.update(world);
  31055. return this;
  31056. };
  31057. /**
  31058. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31059. * Boolean returned.
  31060. */
  31061. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31062. var boundingInfo = this.getBoundingInfo();
  31063. if (!boundingInfo) {
  31064. return false;
  31065. }
  31066. return boundingInfo.isInFrustum(frustumPlanes);
  31067. };
  31068. /**
  31069. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31070. * Boolean returned.
  31071. */
  31072. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31073. var boundingInfo = this.getBoundingInfo();
  31074. if (!boundingInfo) {
  31075. return false;
  31076. }
  31077. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31078. };
  31079. /**
  31080. * Renders the submesh.
  31081. * Returns it.
  31082. */
  31083. SubMesh.prototype.render = function (enableAlphaMode) {
  31084. this._renderingMesh.render(this, enableAlphaMode);
  31085. return this;
  31086. };
  31087. /**
  31088. * Returns a new Index Buffer.
  31089. * Type returned : WebGLBuffer.
  31090. */
  31091. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31092. if (!this._linesIndexBuffer) {
  31093. var linesIndices = [];
  31094. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31095. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31096. }
  31097. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31098. this.linesIndexCount = linesIndices.length;
  31099. }
  31100. return this._linesIndexBuffer;
  31101. };
  31102. /**
  31103. * True is the passed Ray intersects the submesh bounding box.
  31104. * Boolean returned.
  31105. */
  31106. SubMesh.prototype.canIntersects = function (ray) {
  31107. var boundingInfo = this.getBoundingInfo();
  31108. if (!boundingInfo) {
  31109. return false;
  31110. }
  31111. return ray.intersectsBox(boundingInfo.boundingBox);
  31112. };
  31113. /**
  31114. * Returns an object IntersectionInfo.
  31115. */
  31116. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31117. var intersectInfo = null;
  31118. var material = this.getMaterial();
  31119. if (!material) {
  31120. return null;
  31121. }
  31122. switch (material.fillMode) {
  31123. case BABYLON.Material.PointListDrawMode:
  31124. case BABYLON.Material.LineListDrawMode:
  31125. case BABYLON.Material.LineLoopDrawMode:
  31126. case BABYLON.Material.LineStripDrawMode:
  31127. case BABYLON.Material.TriangleFanDrawMode:
  31128. case BABYLON.Material.TriangleStripDrawMode:
  31129. return null;
  31130. }
  31131. // LineMesh first as it's also a Mesh...
  31132. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31133. var lineMesh = this._mesh;
  31134. // Line test
  31135. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31136. var p0 = positions[indices[index]];
  31137. var p1 = positions[indices[index + 1]];
  31138. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31139. if (length < 0) {
  31140. continue;
  31141. }
  31142. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31143. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31144. if (fastCheck) {
  31145. break;
  31146. }
  31147. }
  31148. }
  31149. }
  31150. else {
  31151. // Triangles test
  31152. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31153. var p0 = positions[indices[index]];
  31154. var p1 = positions[indices[index + 1]];
  31155. var p2 = positions[indices[index + 2]];
  31156. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31157. if (currentIntersectInfo) {
  31158. if (currentIntersectInfo.distance < 0) {
  31159. continue;
  31160. }
  31161. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31162. intersectInfo = currentIntersectInfo;
  31163. intersectInfo.faceId = index / 3;
  31164. if (fastCheck) {
  31165. break;
  31166. }
  31167. }
  31168. }
  31169. }
  31170. }
  31171. return intersectInfo;
  31172. };
  31173. SubMesh.prototype._rebuild = function () {
  31174. if (this._linesIndexBuffer) {
  31175. this._linesIndexBuffer = null;
  31176. }
  31177. };
  31178. // Clone
  31179. /**
  31180. * Creates a new Submesh from the passed Mesh.
  31181. */
  31182. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31183. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31184. if (!this.IsGlobal) {
  31185. var boundingInfo = this.getBoundingInfo();
  31186. if (!boundingInfo) {
  31187. return result;
  31188. }
  31189. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31190. }
  31191. return result;
  31192. };
  31193. // Dispose
  31194. /**
  31195. * Disposes the Submesh.
  31196. * Returns nothing.
  31197. */
  31198. SubMesh.prototype.dispose = function () {
  31199. if (this._linesIndexBuffer) {
  31200. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31201. this._linesIndexBuffer = null;
  31202. }
  31203. // Remove from mesh
  31204. var index = this._mesh.subMeshes.indexOf(this);
  31205. this._mesh.subMeshes.splice(index, 1);
  31206. };
  31207. // Statics
  31208. /**
  31209. * Creates a new Submesh from the passed parameters :
  31210. * - materialIndex (integer) : the index of the main mesh material.
  31211. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31212. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31213. * - mesh (Mesh) : the main mesh to create the submesh from.
  31214. * - renderingMesh (optional Mesh) : rendering mesh.
  31215. */
  31216. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31217. var minVertexIndex = Number.MAX_VALUE;
  31218. var maxVertexIndex = -Number.MAX_VALUE;
  31219. renderingMesh = (renderingMesh || mesh);
  31220. var indices = renderingMesh.getIndices();
  31221. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31222. var vertexIndex = indices[index];
  31223. if (vertexIndex < minVertexIndex)
  31224. minVertexIndex = vertexIndex;
  31225. if (vertexIndex > maxVertexIndex)
  31226. maxVertexIndex = vertexIndex;
  31227. }
  31228. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31229. };
  31230. return SubMesh;
  31231. }(BaseSubMesh));
  31232. BABYLON.SubMesh = SubMesh;
  31233. })(BABYLON || (BABYLON = {}));
  31234. //# sourceMappingURL=babylon.subMesh.js.map
  31235. "use strict";
  31236. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31237. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31238. s = arguments[i];
  31239. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31240. t[p] = s[p];
  31241. }
  31242. return t;
  31243. };
  31244. var BABYLON;
  31245. (function (BABYLON) {
  31246. /**
  31247. * Manages the defines for the Material.
  31248. */
  31249. var MaterialDefines = /** @class */ (function () {
  31250. function MaterialDefines() {
  31251. this._isDirty = true;
  31252. this._areLightsDirty = true;
  31253. this._areAttributesDirty = true;
  31254. this._areTexturesDirty = true;
  31255. this._areFresnelDirty = true;
  31256. this._areMiscDirty = true;
  31257. this._areImageProcessingDirty = true;
  31258. this._normals = false;
  31259. this._uvs = false;
  31260. this._needNormals = false;
  31261. this._needUVs = false;
  31262. }
  31263. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31264. /**
  31265. * Specifies if the material needs to be re-calculated.
  31266. */
  31267. get: function () {
  31268. return this._isDirty;
  31269. },
  31270. enumerable: true,
  31271. configurable: true
  31272. });
  31273. /**
  31274. * Marks the material to indicate that it has been re-calculated.
  31275. */
  31276. MaterialDefines.prototype.markAsProcessed = function () {
  31277. this._isDirty = false;
  31278. this._areAttributesDirty = false;
  31279. this._areTexturesDirty = false;
  31280. this._areFresnelDirty = false;
  31281. this._areLightsDirty = false;
  31282. this._areMiscDirty = false;
  31283. this._areImageProcessingDirty = false;
  31284. };
  31285. /**
  31286. * Marks the material to indicate that it needs to be re-calculated.
  31287. */
  31288. MaterialDefines.prototype.markAsUnprocessed = function () {
  31289. this._isDirty = true;
  31290. };
  31291. /**
  31292. * Marks the material to indicate all of its defines need to be re-calculated.
  31293. */
  31294. MaterialDefines.prototype.markAllAsDirty = function () {
  31295. this._areTexturesDirty = true;
  31296. this._areAttributesDirty = true;
  31297. this._areLightsDirty = true;
  31298. this._areFresnelDirty = true;
  31299. this._areMiscDirty = true;
  31300. this._areImageProcessingDirty = true;
  31301. this._isDirty = true;
  31302. };
  31303. /**
  31304. * Marks the material to indicate that image processing needs to be re-calculated.
  31305. */
  31306. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31307. this._areImageProcessingDirty = true;
  31308. this._isDirty = true;
  31309. };
  31310. /**
  31311. * Marks the material to indicate the lights need to be re-calculated.
  31312. */
  31313. MaterialDefines.prototype.markAsLightDirty = function () {
  31314. this._areLightsDirty = true;
  31315. this._isDirty = true;
  31316. };
  31317. /**
  31318. * Marks the attribute state as changed.
  31319. */
  31320. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31321. this._areAttributesDirty = true;
  31322. this._isDirty = true;
  31323. };
  31324. /**
  31325. * Marks the texture state as changed.
  31326. */
  31327. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31328. this._areTexturesDirty = true;
  31329. this._isDirty = true;
  31330. };
  31331. /**
  31332. * Marks the fresnel state as changed.
  31333. */
  31334. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31335. this._areFresnelDirty = true;
  31336. this._isDirty = true;
  31337. };
  31338. /**
  31339. * Marks the misc state as changed.
  31340. */
  31341. MaterialDefines.prototype.markAsMiscDirty = function () {
  31342. this._areMiscDirty = true;
  31343. this._isDirty = true;
  31344. };
  31345. /**
  31346. * Rebuilds the material defines.
  31347. */
  31348. MaterialDefines.prototype.rebuild = function () {
  31349. if (this._keys) {
  31350. delete this._keys;
  31351. }
  31352. this._keys = [];
  31353. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31354. var key = _a[_i];
  31355. if (key[0] === "_") {
  31356. continue;
  31357. }
  31358. this._keys.push(key);
  31359. }
  31360. };
  31361. /**
  31362. * Specifies if two material defines are equal.
  31363. * @param other - A material define instance to compare to.
  31364. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31365. */
  31366. MaterialDefines.prototype.isEqual = function (other) {
  31367. if (this._keys.length !== other._keys.length) {
  31368. return false;
  31369. }
  31370. for (var index = 0; index < this._keys.length; index++) {
  31371. var prop = this._keys[index];
  31372. if (this[prop] !== other[prop]) {
  31373. return false;
  31374. }
  31375. }
  31376. return true;
  31377. };
  31378. /**
  31379. * Clones this instance's defines to another instance.
  31380. * @param other - material defines to clone values to.
  31381. */
  31382. MaterialDefines.prototype.cloneTo = function (other) {
  31383. if (this._keys.length !== other._keys.length) {
  31384. other._keys = this._keys.slice(0);
  31385. }
  31386. for (var index = 0; index < this._keys.length; index++) {
  31387. var prop = this._keys[index];
  31388. other[prop] = this[prop];
  31389. }
  31390. };
  31391. /**
  31392. * Resets the material define values.
  31393. */
  31394. MaterialDefines.prototype.reset = function () {
  31395. for (var index = 0; index < this._keys.length; index++) {
  31396. var prop = this._keys[index];
  31397. var type = typeof this[prop];
  31398. switch (type) {
  31399. case "number":
  31400. this[prop] = 0;
  31401. break;
  31402. case "string":
  31403. this[prop] = "";
  31404. break;
  31405. default:
  31406. this[prop] = false;
  31407. break;
  31408. }
  31409. }
  31410. };
  31411. /**
  31412. * Converts the material define values to a string.
  31413. * @returns - String of material define information.
  31414. */
  31415. MaterialDefines.prototype.toString = function () {
  31416. var result = "";
  31417. for (var index = 0; index < this._keys.length; index++) {
  31418. var prop = this._keys[index];
  31419. var value = this[prop];
  31420. var type = typeof value;
  31421. switch (type) {
  31422. case "number":
  31423. case "string":
  31424. result += "#define " + prop + " " + value + "\n";
  31425. break;
  31426. default:
  31427. if (value) {
  31428. result += "#define " + prop + "\n";
  31429. }
  31430. break;
  31431. }
  31432. }
  31433. return result;
  31434. };
  31435. return MaterialDefines;
  31436. }());
  31437. BABYLON.MaterialDefines = MaterialDefines;
  31438. /**
  31439. * This offers the main features of a material in BJS.
  31440. */
  31441. var Material = /** @class */ (function () {
  31442. /**
  31443. * Creates a material instance.
  31444. * @param name - The name of the material.
  31445. * @param scene - The BJS scene to reference.
  31446. * @param doNotAdd - Specifies if the material should be added to the scene.
  31447. */
  31448. function Material(name, scene, doNotAdd) {
  31449. /**
  31450. * Specifies if the ready state should be checked on each call.
  31451. */
  31452. this.checkReadyOnEveryCall = false;
  31453. /**
  31454. * Specifies if the ready state should be checked once.
  31455. */
  31456. this.checkReadyOnlyOnce = false;
  31457. /**
  31458. * The state of the material.
  31459. */
  31460. this.state = "";
  31461. /**
  31462. * The alpha value of the material.
  31463. */
  31464. this._alpha = 1.0;
  31465. /**
  31466. * Specifies if back face culling is enabled.
  31467. */
  31468. this._backFaceCulling = true;
  31469. /**
  31470. * Specifies if the material should be serialized.
  31471. */
  31472. this.doNotSerialize = false;
  31473. /**
  31474. * Specifies if the effect should be stored on sub meshes.
  31475. */
  31476. this.storeEffectOnSubMeshes = false;
  31477. /**
  31478. * An event triggered when the material is disposed.
  31479. * @type {BABYLON.Observable}
  31480. */
  31481. this.onDisposeObservable = new BABYLON.Observable();
  31482. /**
  31483. * An event triggered when the material is bound.
  31484. * @type {BABYLON.Observable}
  31485. */
  31486. this.onBindObservable = new BABYLON.Observable();
  31487. /**
  31488. * An event triggered when the material is unbound.
  31489. * @type {BABYLON.Observable}
  31490. */
  31491. this.onUnBindObservable = new BABYLON.Observable();
  31492. /**
  31493. * Stores the value of the alpha mode.
  31494. */
  31495. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31496. /**
  31497. * Stores the state of the need depth pre-pass value.
  31498. */
  31499. this._needDepthPrePass = false;
  31500. /**
  31501. * Specifies if depth writing should be disabled.
  31502. */
  31503. this.disableDepthWrite = false;
  31504. /**
  31505. * Specifies if depth writing should be forced.
  31506. */
  31507. this.forceDepthWrite = false;
  31508. /**
  31509. * Specifies if there should be a separate pass for culling.
  31510. */
  31511. this.separateCullingPass = false;
  31512. /**
  31513. * Stores the state specifing if fog should be enabled.
  31514. */
  31515. this._fogEnabled = true;
  31516. /**
  31517. * Stores the size of points.
  31518. */
  31519. this.pointSize = 1.0;
  31520. /**
  31521. * Stores the z offset value.
  31522. */
  31523. this.zOffset = 0;
  31524. /**
  31525. * Specifies if the material was previously ready.
  31526. */
  31527. this._wasPreviouslyReady = false;
  31528. /**
  31529. * Stores the fill mode state.
  31530. */
  31531. this._fillMode = Material.TriangleFillMode;
  31532. this.name = name;
  31533. this.id = name || BABYLON.Tools.RandomId();
  31534. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31535. if (this._scene.useRightHandedSystem) {
  31536. this.sideOrientation = Material.ClockWiseSideOrientation;
  31537. }
  31538. else {
  31539. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31540. }
  31541. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31542. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31543. if (!doNotAdd) {
  31544. this._scene.materials.push(this);
  31545. }
  31546. }
  31547. Object.defineProperty(Material, "TriangleFillMode", {
  31548. /**
  31549. * Returns the triangle fill mode.
  31550. */
  31551. get: function () {
  31552. return Material._TriangleFillMode;
  31553. },
  31554. enumerable: true,
  31555. configurable: true
  31556. });
  31557. Object.defineProperty(Material, "WireFrameFillMode", {
  31558. /**
  31559. * Returns the wireframe mode.
  31560. */
  31561. get: function () {
  31562. return Material._WireFrameFillMode;
  31563. },
  31564. enumerable: true,
  31565. configurable: true
  31566. });
  31567. Object.defineProperty(Material, "PointFillMode", {
  31568. /**
  31569. * Returns the point fill mode.
  31570. */
  31571. get: function () {
  31572. return Material._PointFillMode;
  31573. },
  31574. enumerable: true,
  31575. configurable: true
  31576. });
  31577. Object.defineProperty(Material, "PointListDrawMode", {
  31578. /**
  31579. * Returns the point list draw mode.
  31580. */
  31581. get: function () {
  31582. return Material._PointListDrawMode;
  31583. },
  31584. enumerable: true,
  31585. configurable: true
  31586. });
  31587. Object.defineProperty(Material, "LineListDrawMode", {
  31588. /**
  31589. * Returns the line list draw mode.
  31590. */
  31591. get: function () {
  31592. return Material._LineListDrawMode;
  31593. },
  31594. enumerable: true,
  31595. configurable: true
  31596. });
  31597. Object.defineProperty(Material, "LineLoopDrawMode", {
  31598. /**
  31599. * Returns the line loop draw mode.
  31600. */
  31601. get: function () {
  31602. return Material._LineLoopDrawMode;
  31603. },
  31604. enumerable: true,
  31605. configurable: true
  31606. });
  31607. Object.defineProperty(Material, "LineStripDrawMode", {
  31608. /**
  31609. * Returns the line strip draw mode.
  31610. */
  31611. get: function () {
  31612. return Material._LineStripDrawMode;
  31613. },
  31614. enumerable: true,
  31615. configurable: true
  31616. });
  31617. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31618. /**
  31619. * Returns the triangle strip draw mode.
  31620. */
  31621. get: function () {
  31622. return Material._TriangleStripDrawMode;
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31628. /**
  31629. * Returns the triangle fan draw mode.
  31630. */
  31631. get: function () {
  31632. return Material._TriangleFanDrawMode;
  31633. },
  31634. enumerable: true,
  31635. configurable: true
  31636. });
  31637. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31638. /**
  31639. * Returns the clock-wise side orientation.
  31640. */
  31641. get: function () {
  31642. return Material._ClockWiseSideOrientation;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31648. /**
  31649. * Returns the counter clock-wise side orientation.
  31650. */
  31651. get: function () {
  31652. return Material._CounterClockWiseSideOrientation;
  31653. },
  31654. enumerable: true,
  31655. configurable: true
  31656. });
  31657. Object.defineProperty(Material, "TextureDirtyFlag", {
  31658. /**
  31659. * Returns the dirty texture flag value.
  31660. */
  31661. get: function () {
  31662. return Material._TextureDirtyFlag;
  31663. },
  31664. enumerable: true,
  31665. configurable: true
  31666. });
  31667. Object.defineProperty(Material, "LightDirtyFlag", {
  31668. /**
  31669. * Returns the dirty light flag value.
  31670. */
  31671. get: function () {
  31672. return Material._LightDirtyFlag;
  31673. },
  31674. enumerable: true,
  31675. configurable: true
  31676. });
  31677. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31678. /**
  31679. * Returns the dirty fresnel flag value.
  31680. */
  31681. get: function () {
  31682. return Material._FresnelDirtyFlag;
  31683. },
  31684. enumerable: true,
  31685. configurable: true
  31686. });
  31687. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31688. /**
  31689. * Returns the dirty attributes flag value.
  31690. */
  31691. get: function () {
  31692. return Material._AttributesDirtyFlag;
  31693. },
  31694. enumerable: true,
  31695. configurable: true
  31696. });
  31697. Object.defineProperty(Material, "MiscDirtyFlag", {
  31698. /**
  31699. * Returns the dirty misc flag value.
  31700. */
  31701. get: function () {
  31702. return Material._MiscDirtyFlag;
  31703. },
  31704. enumerable: true,
  31705. configurable: true
  31706. });
  31707. Object.defineProperty(Material.prototype, "alpha", {
  31708. /**
  31709. * Gets the alpha value of the material.
  31710. */
  31711. get: function () {
  31712. return this._alpha;
  31713. },
  31714. /**
  31715. * Sets the alpha value of the material.
  31716. */
  31717. set: function (value) {
  31718. if (this._alpha === value) {
  31719. return;
  31720. }
  31721. this._alpha = value;
  31722. this.markAsDirty(Material.MiscDirtyFlag);
  31723. },
  31724. enumerable: true,
  31725. configurable: true
  31726. });
  31727. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31728. /**
  31729. * Gets the back-face culling state.
  31730. */
  31731. get: function () {
  31732. return this._backFaceCulling;
  31733. },
  31734. /**
  31735. * Sets the back-face culling state.
  31736. */
  31737. set: function (value) {
  31738. if (this._backFaceCulling === value) {
  31739. return;
  31740. }
  31741. this._backFaceCulling = value;
  31742. this.markAsDirty(Material.TextureDirtyFlag);
  31743. },
  31744. enumerable: true,
  31745. configurable: true
  31746. });
  31747. Object.defineProperty(Material.prototype, "onDispose", {
  31748. /**
  31749. * Called during a dispose event.
  31750. */
  31751. set: function (callback) {
  31752. if (this._onDisposeObserver) {
  31753. this.onDisposeObservable.remove(this._onDisposeObserver);
  31754. }
  31755. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31756. },
  31757. enumerable: true,
  31758. configurable: true
  31759. });
  31760. Object.defineProperty(Material.prototype, "onBind", {
  31761. /**
  31762. * Called during a bind event.
  31763. */
  31764. set: function (callback) {
  31765. if (this._onBindObserver) {
  31766. this.onBindObservable.remove(this._onBindObserver);
  31767. }
  31768. this._onBindObserver = this.onBindObservable.add(callback);
  31769. },
  31770. enumerable: true,
  31771. configurable: true
  31772. });
  31773. Object.defineProperty(Material.prototype, "alphaMode", {
  31774. /**
  31775. * Gets the value of the alpha mode.
  31776. */
  31777. get: function () {
  31778. return this._alphaMode;
  31779. },
  31780. /**
  31781. * Sets the value of the alpha mode.
  31782. *
  31783. * | Value | Type | Description |
  31784. * | --- | --- | --- |
  31785. * | 0 | ALPHA_DISABLE | |
  31786. * | 1 | ALPHA_ADD | |
  31787. * | 2 | ALPHA_COMBINE | |
  31788. * | 3 | ALPHA_SUBTRACT | |
  31789. * | 4 | ALPHA_MULTIPLY | |
  31790. * | 5 | ALPHA_MAXIMIZED | |
  31791. * | 6 | ALPHA_ONEONE | |
  31792. * | 7 | ALPHA_PREMULTIPLIED | |
  31793. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31794. * | 9 | ALPHA_INTERPOLATE | |
  31795. * | 10 | ALPHA_SCREENMODE | |
  31796. *
  31797. */
  31798. set: function (value) {
  31799. if (this._alphaMode === value) {
  31800. return;
  31801. }
  31802. this._alphaMode = value;
  31803. this.markAsDirty(Material.TextureDirtyFlag);
  31804. },
  31805. enumerable: true,
  31806. configurable: true
  31807. });
  31808. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31809. /**
  31810. * Gets the depth pre-pass value.
  31811. */
  31812. get: function () {
  31813. return this._needDepthPrePass;
  31814. },
  31815. /**
  31816. * Sets the need depth pre-pass value.
  31817. */
  31818. set: function (value) {
  31819. if (this._needDepthPrePass === value) {
  31820. return;
  31821. }
  31822. this._needDepthPrePass = value;
  31823. if (this._needDepthPrePass) {
  31824. this.checkReadyOnEveryCall = true;
  31825. }
  31826. },
  31827. enumerable: true,
  31828. configurable: true
  31829. });
  31830. Object.defineProperty(Material.prototype, "fogEnabled", {
  31831. /**
  31832. * Gets the value of the fog enabled state.
  31833. */
  31834. get: function () {
  31835. return this._fogEnabled;
  31836. },
  31837. /**
  31838. * Sets the state for enabling fog.
  31839. */
  31840. set: function (value) {
  31841. if (this._fogEnabled === value) {
  31842. return;
  31843. }
  31844. this._fogEnabled = value;
  31845. this.markAsDirty(Material.MiscDirtyFlag);
  31846. },
  31847. enumerable: true,
  31848. configurable: true
  31849. });
  31850. Object.defineProperty(Material.prototype, "wireframe", {
  31851. /**
  31852. * Gets a value specifying if wireframe mode is enabled.
  31853. */
  31854. get: function () {
  31855. switch (this._fillMode) {
  31856. case Material.WireFrameFillMode:
  31857. case Material.LineListDrawMode:
  31858. case Material.LineLoopDrawMode:
  31859. case Material.LineStripDrawMode:
  31860. return true;
  31861. }
  31862. return this._scene.forceWireframe;
  31863. },
  31864. /**
  31865. * Sets the state of wireframe mode.
  31866. */
  31867. set: function (value) {
  31868. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31869. },
  31870. enumerable: true,
  31871. configurable: true
  31872. });
  31873. Object.defineProperty(Material.prototype, "pointsCloud", {
  31874. /**
  31875. * Gets the value specifying if point clouds are enabled.
  31876. */
  31877. get: function () {
  31878. switch (this._fillMode) {
  31879. case Material.PointFillMode:
  31880. case Material.PointListDrawMode:
  31881. return true;
  31882. }
  31883. return this._scene.forcePointsCloud;
  31884. },
  31885. /**
  31886. * Sets the state of point cloud mode.
  31887. */
  31888. set: function (value) {
  31889. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31890. },
  31891. enumerable: true,
  31892. configurable: true
  31893. });
  31894. Object.defineProperty(Material.prototype, "fillMode", {
  31895. /**
  31896. * Gets the material fill mode.
  31897. */
  31898. get: function () {
  31899. return this._fillMode;
  31900. },
  31901. /**
  31902. * Sets the material fill mode.
  31903. */
  31904. set: function (value) {
  31905. if (this._fillMode === value) {
  31906. return;
  31907. }
  31908. this._fillMode = value;
  31909. this.markAsDirty(Material.MiscDirtyFlag);
  31910. },
  31911. enumerable: true,
  31912. configurable: true
  31913. });
  31914. /**
  31915. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31916. * subclasses should override adding information pertainent to themselves.
  31917. * @returns - String with material information.
  31918. */
  31919. Material.prototype.toString = function (fullDetails) {
  31920. var ret = "Name: " + this.name;
  31921. if (fullDetails) {
  31922. }
  31923. return ret;
  31924. };
  31925. /**
  31926. * Gets the class name of the material.
  31927. * @returns - String with the class name of the material.
  31928. */
  31929. Material.prototype.getClassName = function () {
  31930. return "Material";
  31931. };
  31932. Object.defineProperty(Material.prototype, "isFrozen", {
  31933. /**
  31934. * Specifies if updates for the material been locked.
  31935. */
  31936. get: function () {
  31937. return this.checkReadyOnlyOnce;
  31938. },
  31939. enumerable: true,
  31940. configurable: true
  31941. });
  31942. /**
  31943. * Locks updates for the material.
  31944. */
  31945. Material.prototype.freeze = function () {
  31946. this.checkReadyOnlyOnce = true;
  31947. };
  31948. /**
  31949. * Unlocks updates for the material.
  31950. */
  31951. Material.prototype.unfreeze = function () {
  31952. this.checkReadyOnlyOnce = false;
  31953. };
  31954. /**
  31955. * Specifies if the material is ready to be used.
  31956. * @param mesh - BJS mesh.
  31957. * @param useInstances - Specifies if instances should be used.
  31958. * @returns - Boolean indicating if the material is ready to be used.
  31959. */
  31960. Material.prototype.isReady = function (mesh, useInstances) {
  31961. return true;
  31962. };
  31963. /**
  31964. * Specifies that the submesh is ready to be used.
  31965. * @param mesh - BJS mesh.
  31966. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31967. * @param useInstances - Specifies that instances should be used.
  31968. * @returns - boolean indicating that the submesh is ready or not.
  31969. */
  31970. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31971. return false;
  31972. };
  31973. /**
  31974. * Returns the material effect.
  31975. * @returns - Nullable material effect.
  31976. */
  31977. Material.prototype.getEffect = function () {
  31978. return this._effect;
  31979. };
  31980. /**
  31981. * Returns the BJS scene.
  31982. * @returns - BJS Scene.
  31983. */
  31984. Material.prototype.getScene = function () {
  31985. return this._scene;
  31986. };
  31987. /**
  31988. * Specifies if the material will require alpha blending
  31989. * @returns - Boolean specifying if alpha blending is needed.
  31990. */
  31991. Material.prototype.needAlphaBlending = function () {
  31992. return (this.alpha < 1.0);
  31993. };
  31994. /**
  31995. * Specifies if the mesh will require alpha blending.
  31996. * @param mesh - BJS mesh.
  31997. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31998. */
  31999. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  32000. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  32001. };
  32002. /**
  32003. * Specifies if this material should be rendered in alpha test mode.
  32004. * @returns - Boolean specifying if an alpha test is needed.
  32005. */
  32006. Material.prototype.needAlphaTesting = function () {
  32007. return false;
  32008. };
  32009. /**
  32010. * Gets the texture used for the alpha test.
  32011. * @returns - Nullable alpha test texture.
  32012. */
  32013. Material.prototype.getAlphaTestTexture = function () {
  32014. return null;
  32015. };
  32016. /**
  32017. * Marks the material to indicate that it needs to be re-calculated.
  32018. */
  32019. Material.prototype.markDirty = function () {
  32020. this._wasPreviouslyReady = false;
  32021. };
  32022. Material.prototype._preBind = function (effect, overrideOrientation) {
  32023. if (overrideOrientation === void 0) { overrideOrientation = null; }
  32024. var engine = this._scene.getEngine();
  32025. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  32026. var reverse = orientation === Material.ClockWiseSideOrientation;
  32027. engine.enableEffect(effect ? effect : this._effect);
  32028. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  32029. return reverse;
  32030. };
  32031. /**
  32032. * Binds the material to the mesh.
  32033. * @param world - World transformation matrix.
  32034. * @param mesh - Mesh to bind the material to.
  32035. */
  32036. Material.prototype.bind = function (world, mesh) {
  32037. };
  32038. /**
  32039. * Binds the submesh to the material.
  32040. * @param world - World transformation matrix.
  32041. * @param mesh - Mesh containing the submesh.
  32042. * @param subMesh - Submesh to bind the material to.
  32043. */
  32044. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32045. };
  32046. /**
  32047. * Binds the world matrix to the material.
  32048. * @param world - World transformation matrix.
  32049. */
  32050. Material.prototype.bindOnlyWorldMatrix = function (world) {
  32051. };
  32052. /**
  32053. * Binds the scene's uniform buffer to the effect.
  32054. * @param effect - Effect to bind to the scene uniform buffer.
  32055. * @param sceneUbo - Scene uniform buffer.
  32056. */
  32057. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32058. sceneUbo.bindToEffect(effect, "Scene");
  32059. };
  32060. /**
  32061. * Binds the view matrix to the effect.
  32062. * @param effect - Effect to bind the view matrix to.
  32063. */
  32064. Material.prototype.bindView = function (effect) {
  32065. if (!this._useUBO) {
  32066. effect.setMatrix("view", this.getScene().getViewMatrix());
  32067. }
  32068. else {
  32069. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32070. }
  32071. };
  32072. /**
  32073. * Binds the view projection matrix to the effect.
  32074. * @param effect - Effect to bind the view projection matrix to.
  32075. */
  32076. Material.prototype.bindViewProjection = function (effect) {
  32077. if (!this._useUBO) {
  32078. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32079. }
  32080. else {
  32081. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32082. }
  32083. };
  32084. /**
  32085. * Specifies if material alpha testing should be turned on for the mesh.
  32086. * @param mesh - BJS mesh.
  32087. */
  32088. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32089. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32090. };
  32091. /**
  32092. * Processes to execute after binding the material to a mesh.
  32093. * @param mesh - BJS mesh.
  32094. */
  32095. Material.prototype._afterBind = function (mesh) {
  32096. this._scene._cachedMaterial = this;
  32097. if (mesh) {
  32098. this._scene._cachedVisibility = mesh.visibility;
  32099. }
  32100. else {
  32101. this._scene._cachedVisibility = 1;
  32102. }
  32103. if (mesh) {
  32104. this.onBindObservable.notifyObservers(mesh);
  32105. }
  32106. if (this.disableDepthWrite) {
  32107. var engine = this._scene.getEngine();
  32108. this._cachedDepthWriteState = engine.getDepthWrite();
  32109. engine.setDepthWrite(false);
  32110. }
  32111. };
  32112. /**
  32113. * Unbinds the material from the mesh.
  32114. */
  32115. Material.prototype.unbind = function () {
  32116. this.onUnBindObservable.notifyObservers(this);
  32117. if (this.disableDepthWrite) {
  32118. var engine = this._scene.getEngine();
  32119. engine.setDepthWrite(this._cachedDepthWriteState);
  32120. }
  32121. };
  32122. /**
  32123. * Gets the active textures from the material.
  32124. * @returns - Array of textures.
  32125. */
  32126. Material.prototype.getActiveTextures = function () {
  32127. return [];
  32128. };
  32129. /**
  32130. * Specifies if the material uses a texture.
  32131. * @param texture - Texture to check against the material.
  32132. * @returns - Boolean specifying if the material uses the texture.
  32133. */
  32134. Material.prototype.hasTexture = function (texture) {
  32135. return false;
  32136. };
  32137. /**
  32138. * Makes a duplicate of the material, and gives it a new name.
  32139. * @param name - Name to call the duplicated material.
  32140. * @returns - Nullable cloned material
  32141. */
  32142. Material.prototype.clone = function (name) {
  32143. return null;
  32144. };
  32145. /**
  32146. * Gets the meshes bound to the material.
  32147. * @returns - Array of meshes bound to the material.
  32148. */
  32149. Material.prototype.getBindedMeshes = function () {
  32150. var result = new Array();
  32151. for (var index = 0; index < this._scene.meshes.length; index++) {
  32152. var mesh = this._scene.meshes[index];
  32153. if (mesh.material === this) {
  32154. result.push(mesh);
  32155. }
  32156. }
  32157. return result;
  32158. };
  32159. /**
  32160. * Force shader compilation
  32161. * @param mesh - BJS mesh.
  32162. * @param onCompiled - function to execute once the material is compiled.
  32163. * @param options - options to pass to this function.
  32164. */
  32165. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32166. var _this = this;
  32167. var localOptions = __assign({ clipPlane: false }, options);
  32168. var subMesh = new BABYLON.BaseSubMesh();
  32169. var scene = this.getScene();
  32170. var checkReady = function () {
  32171. if (!_this._scene || !_this._scene.getEngine()) {
  32172. return;
  32173. }
  32174. if (subMesh._materialDefines) {
  32175. subMesh._materialDefines._renderId = -1;
  32176. }
  32177. var clipPlaneState = scene.clipPlane;
  32178. if (localOptions.clipPlane) {
  32179. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32180. }
  32181. if (_this.storeEffectOnSubMeshes) {
  32182. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32183. if (onCompiled) {
  32184. onCompiled(_this);
  32185. }
  32186. }
  32187. else {
  32188. setTimeout(checkReady, 16);
  32189. }
  32190. }
  32191. else {
  32192. if (_this.isReady(mesh)) {
  32193. if (onCompiled) {
  32194. onCompiled(_this);
  32195. }
  32196. }
  32197. else {
  32198. setTimeout(checkReady, 16);
  32199. }
  32200. }
  32201. if (localOptions.clipPlane) {
  32202. scene.clipPlane = clipPlaneState;
  32203. }
  32204. };
  32205. checkReady();
  32206. };
  32207. /**
  32208. * Force shader compilation.
  32209. * @param mesh The mesh that will use this material
  32210. * @param options Additional options for compiling the shaders
  32211. * @returns A promise that resolves when the compilation completes
  32212. */
  32213. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32214. var _this = this;
  32215. return new Promise(function (resolve) {
  32216. _this.forceCompilation(mesh, function () {
  32217. resolve();
  32218. }, options);
  32219. });
  32220. };
  32221. /**
  32222. * Marks a define in the material to indicate that it needs to be re-computed.
  32223. * @param flag - Material define flag.
  32224. */
  32225. Material.prototype.markAsDirty = function (flag) {
  32226. if (flag & Material.TextureDirtyFlag) {
  32227. this._markAllSubMeshesAsTexturesDirty();
  32228. }
  32229. if (flag & Material.LightDirtyFlag) {
  32230. this._markAllSubMeshesAsLightsDirty();
  32231. }
  32232. if (flag & Material.FresnelDirtyFlag) {
  32233. this._markAllSubMeshesAsFresnelDirty();
  32234. }
  32235. if (flag & Material.AttributesDirtyFlag) {
  32236. this._markAllSubMeshesAsAttributesDirty();
  32237. }
  32238. if (flag & Material.MiscDirtyFlag) {
  32239. this._markAllSubMeshesAsMiscDirty();
  32240. }
  32241. this.getScene().resetCachedMaterial();
  32242. };
  32243. /**
  32244. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32245. * @param func - function which checks material defines against the submeshes.
  32246. */
  32247. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32248. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32249. var mesh = _a[_i];
  32250. if (!mesh.subMeshes) {
  32251. continue;
  32252. }
  32253. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32254. var subMesh = _c[_b];
  32255. if (subMesh.getMaterial() !== this) {
  32256. continue;
  32257. }
  32258. if (!subMesh._materialDefines) {
  32259. continue;
  32260. }
  32261. func(subMesh._materialDefines);
  32262. }
  32263. }
  32264. };
  32265. /**
  32266. * Indicates that image processing needs to be re-calculated for all submeshes.
  32267. */
  32268. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32269. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32270. };
  32271. /**
  32272. * Indicates that textures need to be re-calculated for all submeshes.
  32273. */
  32274. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32275. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32276. };
  32277. /**
  32278. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32279. */
  32280. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32281. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32282. };
  32283. /**
  32284. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32285. */
  32286. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32287. this._markAllSubMeshesAsDirty(function (defines) {
  32288. defines.markAsFresnelDirty();
  32289. defines.markAsMiscDirty();
  32290. });
  32291. };
  32292. /**
  32293. * Indicates that lights need to be re-calculated for all submeshes.
  32294. */
  32295. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32296. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32297. };
  32298. /**
  32299. * Indicates that attributes need to be re-calculated for all submeshes.
  32300. */
  32301. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32302. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32303. };
  32304. /**
  32305. * Indicates that misc needs to be re-calculated for all submeshes.
  32306. */
  32307. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32308. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32309. };
  32310. /**
  32311. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32312. */
  32313. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32314. this._markAllSubMeshesAsDirty(function (defines) {
  32315. defines.markAsTexturesDirty();
  32316. defines.markAsMiscDirty();
  32317. });
  32318. };
  32319. /**
  32320. * Disposes the material.
  32321. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32322. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32323. */
  32324. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32325. // Animations
  32326. this.getScene().stopAnimation(this);
  32327. this.getScene().freeProcessedMaterials();
  32328. // Remove from scene
  32329. var index = this._scene.materials.indexOf(this);
  32330. if (index >= 0) {
  32331. this._scene.materials.splice(index, 1);
  32332. }
  32333. // Remove from meshes
  32334. for (index = 0; index < this._scene.meshes.length; index++) {
  32335. var mesh = this._scene.meshes[index];
  32336. if (mesh.material === this) {
  32337. mesh.material = null;
  32338. if (mesh.geometry) {
  32339. var geometry = (mesh.geometry);
  32340. if (this.storeEffectOnSubMeshes) {
  32341. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32342. var subMesh = _a[_i];
  32343. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32344. if (forceDisposeEffect && subMesh._materialEffect) {
  32345. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32346. }
  32347. }
  32348. }
  32349. else {
  32350. geometry._releaseVertexArrayObject(this._effect);
  32351. }
  32352. }
  32353. }
  32354. }
  32355. this._uniformBuffer.dispose();
  32356. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32357. if (forceDisposeEffect && this._effect) {
  32358. if (!this.storeEffectOnSubMeshes) {
  32359. this._scene.getEngine()._releaseEffect(this._effect);
  32360. }
  32361. this._effect = null;
  32362. }
  32363. // Callback
  32364. this.onDisposeObservable.notifyObservers(this);
  32365. this.onDisposeObservable.clear();
  32366. this.onBindObservable.clear();
  32367. this.onUnBindObservable.clear();
  32368. };
  32369. /**
  32370. * Serializes this material.
  32371. * @returns - serialized material object.
  32372. */
  32373. Material.prototype.serialize = function () {
  32374. return BABYLON.SerializationHelper.Serialize(this);
  32375. };
  32376. /**
  32377. * Creates a MultiMaterial from parse MultiMaterial data.
  32378. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32379. * @param scene - BJS scene.
  32380. * @returns - MultiMaterial.
  32381. */
  32382. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32383. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32384. multiMaterial.id = parsedMultiMaterial.id;
  32385. if (BABYLON.Tags) {
  32386. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32387. }
  32388. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32389. var subMatId = parsedMultiMaterial.materials[matIndex];
  32390. if (subMatId) {
  32391. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32392. }
  32393. else {
  32394. multiMaterial.subMaterials.push(null);
  32395. }
  32396. }
  32397. return multiMaterial;
  32398. };
  32399. /**
  32400. * Creates a material from parsed material data.
  32401. * @param parsedMaterial - Parsed material data.
  32402. * @param scene - BJS scene.
  32403. * @param rootUrl - Root URL containing the material information.
  32404. * @returns - Parsed material.
  32405. */
  32406. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32407. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32408. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32409. }
  32410. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32411. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32412. if (!BABYLON.LegacyPBRMaterial) {
  32413. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32414. return;
  32415. }
  32416. }
  32417. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32418. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32419. ;
  32420. };
  32421. // Triangle views
  32422. Material._TriangleFillMode = 0;
  32423. Material._WireFrameFillMode = 1;
  32424. Material._PointFillMode = 2;
  32425. // Draw modes
  32426. Material._PointListDrawMode = 3;
  32427. Material._LineListDrawMode = 4;
  32428. Material._LineLoopDrawMode = 5;
  32429. Material._LineStripDrawMode = 6;
  32430. Material._TriangleStripDrawMode = 7;
  32431. Material._TriangleFanDrawMode = 8;
  32432. /**
  32433. * Stores the clock-wise side orientation.
  32434. */
  32435. Material._ClockWiseSideOrientation = 0;
  32436. /**
  32437. * Stores the counter clock-wise side orientation.
  32438. */
  32439. Material._CounterClockWiseSideOrientation = 1;
  32440. /**
  32441. * The dirty texture flag value.
  32442. */
  32443. Material._TextureDirtyFlag = 1;
  32444. /**
  32445. * The dirty light flag value.
  32446. */
  32447. Material._LightDirtyFlag = 2;
  32448. /**
  32449. * The dirty fresnel flag value.
  32450. */
  32451. Material._FresnelDirtyFlag = 4;
  32452. /**
  32453. * The dirty attribute flag value.
  32454. */
  32455. Material._AttributesDirtyFlag = 8;
  32456. /**
  32457. * The dirty misc flag value.
  32458. */
  32459. Material._MiscDirtyFlag = 16;
  32460. __decorate([
  32461. BABYLON.serialize()
  32462. ], Material.prototype, "id", void 0);
  32463. __decorate([
  32464. BABYLON.serialize()
  32465. ], Material.prototype, "name", void 0);
  32466. __decorate([
  32467. BABYLON.serialize()
  32468. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32469. __decorate([
  32470. BABYLON.serialize()
  32471. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32472. __decorate([
  32473. BABYLON.serialize()
  32474. ], Material.prototype, "state", void 0);
  32475. __decorate([
  32476. BABYLON.serialize("alpha")
  32477. ], Material.prototype, "_alpha", void 0);
  32478. __decorate([
  32479. BABYLON.serialize("backFaceCulling")
  32480. ], Material.prototype, "_backFaceCulling", void 0);
  32481. __decorate([
  32482. BABYLON.serialize()
  32483. ], Material.prototype, "sideOrientation", void 0);
  32484. __decorate([
  32485. BABYLON.serialize("alphaMode")
  32486. ], Material.prototype, "_alphaMode", void 0);
  32487. __decorate([
  32488. BABYLON.serialize()
  32489. ], Material.prototype, "_needDepthPrePass", void 0);
  32490. __decorate([
  32491. BABYLON.serialize()
  32492. ], Material.prototype, "disableDepthWrite", void 0);
  32493. __decorate([
  32494. BABYLON.serialize()
  32495. ], Material.prototype, "forceDepthWrite", void 0);
  32496. __decorate([
  32497. BABYLON.serialize()
  32498. ], Material.prototype, "separateCullingPass", void 0);
  32499. __decorate([
  32500. BABYLON.serialize("fogEnabled")
  32501. ], Material.prototype, "_fogEnabled", void 0);
  32502. __decorate([
  32503. BABYLON.serialize()
  32504. ], Material.prototype, "pointSize", void 0);
  32505. __decorate([
  32506. BABYLON.serialize()
  32507. ], Material.prototype, "zOffset", void 0);
  32508. __decorate([
  32509. BABYLON.serialize()
  32510. ], Material.prototype, "wireframe", null);
  32511. __decorate([
  32512. BABYLON.serialize()
  32513. ], Material.prototype, "pointsCloud", null);
  32514. __decorate([
  32515. BABYLON.serialize()
  32516. ], Material.prototype, "fillMode", null);
  32517. return Material;
  32518. }());
  32519. BABYLON.Material = Material;
  32520. })(BABYLON || (BABYLON = {}));
  32521. //# sourceMappingURL=babylon.material.js.map
  32522. "use strict";
  32523. var BABYLON;
  32524. (function (BABYLON) {
  32525. var UniformBuffer = /** @class */ (function () {
  32526. /**
  32527. * Uniform buffer objects.
  32528. *
  32529. * Handles blocks of uniform on the GPU.
  32530. *
  32531. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32532. *
  32533. * For more information, please refer to :
  32534. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32535. */
  32536. function UniformBuffer(engine, data, dynamic) {
  32537. this._engine = engine;
  32538. this._noUBO = !engine.supportsUniformBuffers;
  32539. this._dynamic = dynamic;
  32540. this._data = data || [];
  32541. this._uniformLocations = {};
  32542. this._uniformSizes = {};
  32543. this._uniformLocationPointer = 0;
  32544. this._needSync = false;
  32545. if (this._noUBO) {
  32546. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32547. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32548. this.updateFloat = this._updateFloatForEffect;
  32549. this.updateFloat2 = this._updateFloat2ForEffect;
  32550. this.updateFloat3 = this._updateFloat3ForEffect;
  32551. this.updateFloat4 = this._updateFloat4ForEffect;
  32552. this.updateMatrix = this._updateMatrixForEffect;
  32553. this.updateVector3 = this._updateVector3ForEffect;
  32554. this.updateVector4 = this._updateVector4ForEffect;
  32555. this.updateColor3 = this._updateColor3ForEffect;
  32556. this.updateColor4 = this._updateColor4ForEffect;
  32557. }
  32558. else {
  32559. this._engine._uniformBuffers.push(this);
  32560. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32561. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32562. this.updateFloat = this._updateFloatForUniform;
  32563. this.updateFloat2 = this._updateFloat2ForUniform;
  32564. this.updateFloat3 = this._updateFloat3ForUniform;
  32565. this.updateFloat4 = this._updateFloat4ForUniform;
  32566. this.updateMatrix = this._updateMatrixForUniform;
  32567. this.updateVector3 = this._updateVector3ForUniform;
  32568. this.updateVector4 = this._updateVector4ForUniform;
  32569. this.updateColor3 = this._updateColor3ForUniform;
  32570. this.updateColor4 = this._updateColor4ForUniform;
  32571. }
  32572. }
  32573. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32574. // Properties
  32575. /**
  32576. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32577. * or just falling back on setUniformXXX calls.
  32578. */
  32579. get: function () {
  32580. return !this._noUBO;
  32581. },
  32582. enumerable: true,
  32583. configurable: true
  32584. });
  32585. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32586. /**
  32587. * Indicates if the WebGL underlying uniform buffer is in sync
  32588. * with the javascript cache data.
  32589. */
  32590. get: function () {
  32591. return !this._needSync;
  32592. },
  32593. enumerable: true,
  32594. configurable: true
  32595. });
  32596. /**
  32597. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32598. * Also, a dynamic UniformBuffer will disable cache verification and always
  32599. * update the underlying WebGL uniform buffer to the GPU.
  32600. */
  32601. UniformBuffer.prototype.isDynamic = function () {
  32602. return this._dynamic !== undefined;
  32603. };
  32604. /**
  32605. * The data cache on JS side.
  32606. */
  32607. UniformBuffer.prototype.getData = function () {
  32608. return this._bufferData;
  32609. };
  32610. /**
  32611. * The underlying WebGL Uniform buffer.
  32612. */
  32613. UniformBuffer.prototype.getBuffer = function () {
  32614. return this._buffer;
  32615. };
  32616. /**
  32617. * std140 layout specifies how to align data within an UBO structure.
  32618. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32619. * for specs.
  32620. */
  32621. UniformBuffer.prototype._fillAlignment = function (size) {
  32622. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32623. // and 4x4 matrices
  32624. // TODO : change if other types are used
  32625. var alignment;
  32626. if (size <= 2) {
  32627. alignment = size;
  32628. }
  32629. else {
  32630. alignment = 4;
  32631. }
  32632. if ((this._uniformLocationPointer % alignment) !== 0) {
  32633. var oldPointer = this._uniformLocationPointer;
  32634. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32635. var diff = this._uniformLocationPointer - oldPointer;
  32636. for (var i = 0; i < diff; i++) {
  32637. this._data.push(0);
  32638. }
  32639. }
  32640. };
  32641. /**
  32642. * Adds an uniform in the buffer.
  32643. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32644. * for the layout to be correct !
  32645. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32646. * @param {number|number[]} size Data size, or data directly.
  32647. */
  32648. UniformBuffer.prototype.addUniform = function (name, size) {
  32649. if (this._noUBO) {
  32650. return;
  32651. }
  32652. if (this._uniformLocations[name] !== undefined) {
  32653. // Already existing uniform
  32654. return;
  32655. }
  32656. // This function must be called in the order of the shader layout !
  32657. // size can be the size of the uniform, or data directly
  32658. var data;
  32659. if (size instanceof Array) {
  32660. data = size;
  32661. size = data.length;
  32662. }
  32663. else {
  32664. size = size;
  32665. data = [];
  32666. // Fill with zeros
  32667. for (var i = 0; i < size; i++) {
  32668. data.push(0);
  32669. }
  32670. }
  32671. this._fillAlignment(size);
  32672. this._uniformSizes[name] = size;
  32673. this._uniformLocations[name] = this._uniformLocationPointer;
  32674. this._uniformLocationPointer += size;
  32675. for (var i = 0; i < size; i++) {
  32676. this._data.push(data[i]);
  32677. }
  32678. this._needSync = true;
  32679. };
  32680. /**
  32681. * Wrapper for addUniform.
  32682. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32683. * @param {Matrix} mat A 4x4 matrix.
  32684. */
  32685. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32686. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32687. };
  32688. /**
  32689. * Wrapper for addUniform.
  32690. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32691. * @param {number} x
  32692. * @param {number} y
  32693. */
  32694. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32695. var temp = [x, y];
  32696. this.addUniform(name, temp);
  32697. };
  32698. /**
  32699. * Wrapper for addUniform.
  32700. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32701. * @param {number} x
  32702. * @param {number} y
  32703. * @param {number} z
  32704. */
  32705. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32706. var temp = [x, y, z];
  32707. this.addUniform(name, temp);
  32708. };
  32709. /**
  32710. * Wrapper for addUniform.
  32711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32712. * @param {Color3} color
  32713. */
  32714. UniformBuffer.prototype.addColor3 = function (name, color) {
  32715. var temp = new Array();
  32716. color.toArray(temp);
  32717. this.addUniform(name, temp);
  32718. };
  32719. /**
  32720. * Wrapper for addUniform.
  32721. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32722. * @param {Color3} color
  32723. * @param {number} alpha
  32724. */
  32725. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32726. var temp = new Array();
  32727. color.toArray(temp);
  32728. temp.push(alpha);
  32729. this.addUniform(name, temp);
  32730. };
  32731. /**
  32732. * Wrapper for addUniform.
  32733. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32734. * @param {Vector3} vector
  32735. */
  32736. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32737. var temp = new Array();
  32738. vector.toArray(temp);
  32739. this.addUniform(name, temp);
  32740. };
  32741. /**
  32742. * Wrapper for addUniform.
  32743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32744. */
  32745. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32746. this.addUniform(name, 12);
  32747. };
  32748. /**
  32749. * Wrapper for addUniform.
  32750. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32751. */
  32752. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32753. this.addUniform(name, 8);
  32754. };
  32755. /**
  32756. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32757. */
  32758. UniformBuffer.prototype.create = function () {
  32759. if (this._noUBO) {
  32760. return;
  32761. }
  32762. if (this._buffer) {
  32763. return; // nothing to do
  32764. }
  32765. // See spec, alignment must be filled as a vec4
  32766. this._fillAlignment(4);
  32767. this._bufferData = new Float32Array(this._data);
  32768. this._rebuild();
  32769. this._needSync = true;
  32770. };
  32771. UniformBuffer.prototype._rebuild = function () {
  32772. if (this._noUBO) {
  32773. return;
  32774. }
  32775. if (this._dynamic) {
  32776. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32777. }
  32778. else {
  32779. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32780. }
  32781. };
  32782. /**
  32783. * Updates the WebGL Uniform Buffer on the GPU.
  32784. * If the `dynamic` flag is set to true, no cache comparison is done.
  32785. * Otherwise, the buffer will be updated only if the cache differs.
  32786. */
  32787. UniformBuffer.prototype.update = function () {
  32788. if (!this._buffer) {
  32789. this.create();
  32790. return;
  32791. }
  32792. if (!this._dynamic && !this._needSync) {
  32793. return;
  32794. }
  32795. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32796. this._needSync = false;
  32797. };
  32798. /**
  32799. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32800. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32801. * @param {number[]|Float32Array} data Flattened data
  32802. * @param {number} size Size of the data.
  32803. */
  32804. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32805. var location = this._uniformLocations[uniformName];
  32806. if (location === undefined) {
  32807. if (this._buffer) {
  32808. // Cannot add an uniform if the buffer is already created
  32809. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32810. return;
  32811. }
  32812. this.addUniform(uniformName, size);
  32813. location = this._uniformLocations[uniformName];
  32814. }
  32815. if (!this._buffer) {
  32816. this.create();
  32817. }
  32818. if (!this._dynamic) {
  32819. // Cache for static uniform buffers
  32820. var changed = false;
  32821. for (var i = 0; i < size; i++) {
  32822. if (this._bufferData[location + i] !== data[i]) {
  32823. changed = true;
  32824. this._bufferData[location + i] = data[i];
  32825. }
  32826. }
  32827. this._needSync = this._needSync || changed;
  32828. }
  32829. else {
  32830. // No cache for dynamic
  32831. for (var i = 0; i < size; i++) {
  32832. this._bufferData[location + i] = data[i];
  32833. }
  32834. }
  32835. };
  32836. // Update methods
  32837. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32838. // To match std140, matrix must be realigned
  32839. for (var i = 0; i < 3; i++) {
  32840. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32841. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32842. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32843. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32844. }
  32845. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32846. };
  32847. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32848. this._currentEffect.setMatrix3x3(name, matrix);
  32849. };
  32850. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32851. this._currentEffect.setMatrix2x2(name, matrix);
  32852. };
  32853. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32854. // To match std140, matrix must be realigned
  32855. for (var i = 0; i < 2; i++) {
  32856. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32857. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32858. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32859. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32860. }
  32861. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32862. };
  32863. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32864. this._currentEffect.setFloat(name, x);
  32865. };
  32866. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32867. UniformBuffer._tempBuffer[0] = x;
  32868. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32869. };
  32870. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32871. if (suffix === void 0) { suffix = ""; }
  32872. this._currentEffect.setFloat2(name + suffix, x, y);
  32873. };
  32874. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32875. if (suffix === void 0) { suffix = ""; }
  32876. UniformBuffer._tempBuffer[0] = x;
  32877. UniformBuffer._tempBuffer[1] = y;
  32878. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32879. };
  32880. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32881. if (suffix === void 0) { suffix = ""; }
  32882. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32883. };
  32884. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32885. if (suffix === void 0) { suffix = ""; }
  32886. UniformBuffer._tempBuffer[0] = x;
  32887. UniformBuffer._tempBuffer[1] = y;
  32888. UniformBuffer._tempBuffer[2] = z;
  32889. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32890. };
  32891. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32892. if (suffix === void 0) { suffix = ""; }
  32893. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32894. };
  32895. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32896. if (suffix === void 0) { suffix = ""; }
  32897. UniformBuffer._tempBuffer[0] = x;
  32898. UniformBuffer._tempBuffer[1] = y;
  32899. UniformBuffer._tempBuffer[2] = z;
  32900. UniformBuffer._tempBuffer[3] = w;
  32901. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32902. };
  32903. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32904. this._currentEffect.setMatrix(name, mat);
  32905. };
  32906. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32907. this.updateUniform(name, mat.toArray(), 16);
  32908. };
  32909. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32910. this._currentEffect.setVector3(name, vector);
  32911. };
  32912. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32913. vector.toArray(UniformBuffer._tempBuffer);
  32914. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32915. };
  32916. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32917. this._currentEffect.setVector4(name, vector);
  32918. };
  32919. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32920. vector.toArray(UniformBuffer._tempBuffer);
  32921. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32922. };
  32923. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32924. if (suffix === void 0) { suffix = ""; }
  32925. this._currentEffect.setColor3(name + suffix, color);
  32926. };
  32927. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32928. if (suffix === void 0) { suffix = ""; }
  32929. color.toArray(UniformBuffer._tempBuffer);
  32930. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32931. };
  32932. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32933. if (suffix === void 0) { suffix = ""; }
  32934. this._currentEffect.setColor4(name + suffix, color, alpha);
  32935. };
  32936. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32937. if (suffix === void 0) { suffix = ""; }
  32938. color.toArray(UniformBuffer._tempBuffer);
  32939. UniformBuffer._tempBuffer[3] = alpha;
  32940. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32941. };
  32942. /**
  32943. * Sets a sampler uniform on the effect.
  32944. * @param {string} name Name of the sampler.
  32945. * @param {Texture} texture
  32946. */
  32947. UniformBuffer.prototype.setTexture = function (name, texture) {
  32948. this._currentEffect.setTexture(name, texture);
  32949. };
  32950. /**
  32951. * Directly updates the value of the uniform in the cache AND on the GPU.
  32952. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32953. * @param {number[]|Float32Array} data Flattened data
  32954. */
  32955. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32956. this.updateUniform(uniformName, data, data.length);
  32957. this.update();
  32958. };
  32959. /**
  32960. * Binds this uniform buffer to an effect.
  32961. * @param {Effect} effect
  32962. * @param {string} name Name of the uniform block in the shader.
  32963. */
  32964. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32965. this._currentEffect = effect;
  32966. if (this._noUBO || !this._buffer) {
  32967. return;
  32968. }
  32969. effect.bindUniformBuffer(this._buffer, name);
  32970. };
  32971. /**
  32972. * Disposes the uniform buffer.
  32973. */
  32974. UniformBuffer.prototype.dispose = function () {
  32975. if (this._noUBO) {
  32976. return;
  32977. }
  32978. var index = this._engine._uniformBuffers.indexOf(this);
  32979. if (index !== -1) {
  32980. this._engine._uniformBuffers.splice(index, 1);
  32981. }
  32982. if (!this._buffer) {
  32983. return;
  32984. }
  32985. if (this._engine._releaseBuffer(this._buffer)) {
  32986. this._buffer = null;
  32987. }
  32988. };
  32989. // Pool for avoiding memory leaks
  32990. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32991. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32992. return UniformBuffer;
  32993. }());
  32994. BABYLON.UniformBuffer = UniformBuffer;
  32995. })(BABYLON || (BABYLON = {}));
  32996. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32997. "use strict";
  32998. var BABYLON;
  32999. (function (BABYLON) {
  33000. var VertexData = /** @class */ (function () {
  33001. function VertexData() {
  33002. }
  33003. VertexData.prototype.set = function (data, kind) {
  33004. switch (kind) {
  33005. case BABYLON.VertexBuffer.PositionKind:
  33006. this.positions = data;
  33007. break;
  33008. case BABYLON.VertexBuffer.NormalKind:
  33009. this.normals = data;
  33010. break;
  33011. case BABYLON.VertexBuffer.TangentKind:
  33012. this.tangents = data;
  33013. break;
  33014. case BABYLON.VertexBuffer.UVKind:
  33015. this.uvs = data;
  33016. break;
  33017. case BABYLON.VertexBuffer.UV2Kind:
  33018. this.uvs2 = data;
  33019. break;
  33020. case BABYLON.VertexBuffer.UV3Kind:
  33021. this.uvs3 = data;
  33022. break;
  33023. case BABYLON.VertexBuffer.UV4Kind:
  33024. this.uvs4 = data;
  33025. break;
  33026. case BABYLON.VertexBuffer.UV5Kind:
  33027. this.uvs5 = data;
  33028. break;
  33029. case BABYLON.VertexBuffer.UV6Kind:
  33030. this.uvs6 = data;
  33031. break;
  33032. case BABYLON.VertexBuffer.ColorKind:
  33033. this.colors = data;
  33034. break;
  33035. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33036. this.matricesIndices = data;
  33037. break;
  33038. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33039. this.matricesWeights = data;
  33040. break;
  33041. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33042. this.matricesIndicesExtra = data;
  33043. break;
  33044. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33045. this.matricesWeightsExtra = data;
  33046. break;
  33047. }
  33048. };
  33049. /**
  33050. * Associates the vertexData to the passed Mesh.
  33051. * Sets it as updatable or not (default `false`).
  33052. * Returns the VertexData.
  33053. */
  33054. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33055. this._applyTo(mesh, updatable);
  33056. return this;
  33057. };
  33058. /**
  33059. * Associates the vertexData to the passed Geometry.
  33060. * Sets it as updatable or not (default `false`).
  33061. * Returns the VertexData.
  33062. */
  33063. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33064. this._applyTo(geometry, updatable);
  33065. return this;
  33066. };
  33067. /**
  33068. * Updates the associated mesh.
  33069. * Returns the VertexData.
  33070. */
  33071. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33072. this._update(mesh);
  33073. return this;
  33074. };
  33075. /**
  33076. * Updates the associated geometry.
  33077. * Returns the VertexData.
  33078. */
  33079. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33080. this._update(geometry);
  33081. return this;
  33082. };
  33083. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33084. if (updatable === void 0) { updatable = false; }
  33085. if (this.positions) {
  33086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33087. }
  33088. if (this.normals) {
  33089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33090. }
  33091. if (this.tangents) {
  33092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33093. }
  33094. if (this.uvs) {
  33095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33096. }
  33097. if (this.uvs2) {
  33098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33099. }
  33100. if (this.uvs3) {
  33101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33102. }
  33103. if (this.uvs4) {
  33104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33105. }
  33106. if (this.uvs5) {
  33107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33108. }
  33109. if (this.uvs6) {
  33110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33111. }
  33112. if (this.colors) {
  33113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33114. }
  33115. if (this.matricesIndices) {
  33116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33117. }
  33118. if (this.matricesWeights) {
  33119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33120. }
  33121. if (this.matricesIndicesExtra) {
  33122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33123. }
  33124. if (this.matricesWeightsExtra) {
  33125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33126. }
  33127. if (this.indices) {
  33128. meshOrGeometry.setIndices(this.indices, null, updatable);
  33129. }
  33130. return this;
  33131. };
  33132. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33133. if (this.positions) {
  33134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33135. }
  33136. if (this.normals) {
  33137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33138. }
  33139. if (this.tangents) {
  33140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33141. }
  33142. if (this.uvs) {
  33143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33144. }
  33145. if (this.uvs2) {
  33146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33147. }
  33148. if (this.uvs3) {
  33149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33150. }
  33151. if (this.uvs4) {
  33152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33153. }
  33154. if (this.uvs5) {
  33155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33156. }
  33157. if (this.uvs6) {
  33158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33159. }
  33160. if (this.colors) {
  33161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33162. }
  33163. if (this.matricesIndices) {
  33164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33165. }
  33166. if (this.matricesWeights) {
  33167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33168. }
  33169. if (this.matricesIndicesExtra) {
  33170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33171. }
  33172. if (this.matricesWeightsExtra) {
  33173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33174. }
  33175. if (this.indices) {
  33176. meshOrGeometry.setIndices(this.indices, null);
  33177. }
  33178. return this;
  33179. };
  33180. /**
  33181. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33182. * Returns the VertexData.
  33183. */
  33184. VertexData.prototype.transform = function (matrix) {
  33185. var transformed = BABYLON.Vector3.Zero();
  33186. var index;
  33187. if (this.positions) {
  33188. var position = BABYLON.Vector3.Zero();
  33189. for (index = 0; index < this.positions.length; index += 3) {
  33190. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33191. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33192. this.positions[index] = transformed.x;
  33193. this.positions[index + 1] = transformed.y;
  33194. this.positions[index + 2] = transformed.z;
  33195. }
  33196. }
  33197. if (this.normals) {
  33198. var normal = BABYLON.Vector3.Zero();
  33199. for (index = 0; index < this.normals.length; index += 3) {
  33200. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33201. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33202. this.normals[index] = transformed.x;
  33203. this.normals[index + 1] = transformed.y;
  33204. this.normals[index + 2] = transformed.z;
  33205. }
  33206. }
  33207. if (this.tangents) {
  33208. var tangent = BABYLON.Vector4.Zero();
  33209. var tangentTransformed = BABYLON.Vector4.Zero();
  33210. for (index = 0; index < this.tangents.length; index += 4) {
  33211. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33212. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33213. this.tangents[index] = tangentTransformed.x;
  33214. this.tangents[index + 1] = tangentTransformed.y;
  33215. this.tangents[index + 2] = tangentTransformed.z;
  33216. this.tangents[index + 3] = tangentTransformed.w;
  33217. }
  33218. }
  33219. return this;
  33220. };
  33221. /**
  33222. * Merges the passed VertexData into the current one.
  33223. * Returns the modified VertexData.
  33224. */
  33225. VertexData.prototype.merge = function (other) {
  33226. this._validate();
  33227. other._validate();
  33228. if (!this.normals !== !other.normals ||
  33229. !this.tangents !== !other.tangents ||
  33230. !this.uvs !== !other.uvs ||
  33231. !this.uvs2 !== !other.uvs2 ||
  33232. !this.uvs3 !== !other.uvs3 ||
  33233. !this.uvs4 !== !other.uvs4 ||
  33234. !this.uvs5 !== !other.uvs5 ||
  33235. !this.uvs6 !== !other.uvs6 ||
  33236. !this.colors !== !other.colors ||
  33237. !this.matricesIndices !== !other.matricesIndices ||
  33238. !this.matricesWeights !== !other.matricesWeights ||
  33239. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33240. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33241. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33242. }
  33243. if (other.indices) {
  33244. if (!this.indices) {
  33245. this.indices = [];
  33246. }
  33247. var offset = this.positions ? this.positions.length / 3 : 0;
  33248. for (var index = 0; index < other.indices.length; index++) {
  33249. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33250. this.indices.push(other.indices[index] + offset);
  33251. }
  33252. }
  33253. this.positions = this._mergeElement(this.positions, other.positions);
  33254. this.normals = this._mergeElement(this.normals, other.normals);
  33255. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33256. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33257. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33258. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33259. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33260. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33261. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33262. this.colors = this._mergeElement(this.colors, other.colors);
  33263. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33264. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33265. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33266. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33267. return this;
  33268. };
  33269. VertexData.prototype._mergeElement = function (source, other) {
  33270. if (!source) {
  33271. return other;
  33272. }
  33273. if (!other) {
  33274. return source;
  33275. }
  33276. var len = other.length + source.length;
  33277. var isSrcTypedArray = source instanceof Float32Array;
  33278. var isOthTypedArray = other instanceof Float32Array;
  33279. // use non-loop method when the source is Float32Array
  33280. if (isSrcTypedArray) {
  33281. var ret32 = new Float32Array(len);
  33282. ret32.set(source);
  33283. ret32.set(other, source.length);
  33284. return ret32;
  33285. // source is number[], when other is also use concat
  33286. }
  33287. else if (!isOthTypedArray) {
  33288. return source.concat(other);
  33289. // source is a number[], but other is a Float32Array, loop required
  33290. }
  33291. else {
  33292. var ret = source.slice(0); // copy source to a separate array
  33293. for (var i = 0, len = other.length; i < len; i++) {
  33294. ret.push(other[i]);
  33295. }
  33296. return ret;
  33297. }
  33298. };
  33299. VertexData.prototype._validate = function () {
  33300. if (!this.positions) {
  33301. throw new Error("Positions are required");
  33302. }
  33303. var getElementCount = function (kind, values) {
  33304. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33305. if ((values.length % stride) !== 0) {
  33306. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33307. }
  33308. return values.length / stride;
  33309. };
  33310. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33311. var validateElementCount = function (kind, values) {
  33312. var elementCount = getElementCount(kind, values);
  33313. if (elementCount !== positionsElementCount) {
  33314. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33315. }
  33316. };
  33317. if (this.normals)
  33318. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33319. if (this.tangents)
  33320. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33321. if (this.uvs)
  33322. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33323. if (this.uvs2)
  33324. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33325. if (this.uvs3)
  33326. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33327. if (this.uvs4)
  33328. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33329. if (this.uvs5)
  33330. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33331. if (this.uvs6)
  33332. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33333. if (this.colors)
  33334. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33335. if (this.matricesIndices)
  33336. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33337. if (this.matricesWeights)
  33338. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33339. if (this.matricesIndicesExtra)
  33340. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33341. if (this.matricesWeightsExtra)
  33342. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33343. };
  33344. /**
  33345. * Serializes the VertexData.
  33346. * Returns a serialized object.
  33347. */
  33348. VertexData.prototype.serialize = function () {
  33349. var serializationObject = this.serialize();
  33350. if (this.positions) {
  33351. serializationObject.positions = this.positions;
  33352. }
  33353. if (this.normals) {
  33354. serializationObject.normals = this.normals;
  33355. }
  33356. if (this.tangents) {
  33357. serializationObject.tangents = this.tangents;
  33358. }
  33359. if (this.uvs) {
  33360. serializationObject.uvs = this.uvs;
  33361. }
  33362. if (this.uvs2) {
  33363. serializationObject.uvs2 = this.uvs2;
  33364. }
  33365. if (this.uvs3) {
  33366. serializationObject.uvs3 = this.uvs3;
  33367. }
  33368. if (this.uvs4) {
  33369. serializationObject.uvs4 = this.uvs4;
  33370. }
  33371. if (this.uvs5) {
  33372. serializationObject.uvs5 = this.uvs5;
  33373. }
  33374. if (this.uvs6) {
  33375. serializationObject.uvs6 = this.uvs6;
  33376. }
  33377. if (this.colors) {
  33378. serializationObject.colors = this.colors;
  33379. }
  33380. if (this.matricesIndices) {
  33381. serializationObject.matricesIndices = this.matricesIndices;
  33382. serializationObject.matricesIndices._isExpanded = true;
  33383. }
  33384. if (this.matricesWeights) {
  33385. serializationObject.matricesWeights = this.matricesWeights;
  33386. }
  33387. if (this.matricesIndicesExtra) {
  33388. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33389. serializationObject.matricesIndicesExtra._isExpanded = true;
  33390. }
  33391. if (this.matricesWeightsExtra) {
  33392. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33393. }
  33394. serializationObject.indices = this.indices;
  33395. return serializationObject;
  33396. };
  33397. // Statics
  33398. /**
  33399. * Returns the object VertexData associated to the passed mesh.
  33400. */
  33401. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33402. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33403. };
  33404. /**
  33405. * Returns the object VertexData associated to the passed geometry.
  33406. */
  33407. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33408. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33409. };
  33410. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33411. var result = new VertexData();
  33412. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33413. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33414. }
  33415. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33416. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33417. }
  33418. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33419. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33420. }
  33421. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33422. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33423. }
  33424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33425. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33426. }
  33427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33428. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33429. }
  33430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33431. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33432. }
  33433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33434. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33435. }
  33436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33437. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33438. }
  33439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33440. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33441. }
  33442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33443. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33444. }
  33445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33446. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33447. }
  33448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33449. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33450. }
  33451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33452. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33453. }
  33454. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33455. return result;
  33456. };
  33457. /**
  33458. * Creates the vertexData of the Ribbon.
  33459. */
  33460. VertexData.CreateRibbon = function (options) {
  33461. var pathArray = options.pathArray;
  33462. var closeArray = options.closeArray || false;
  33463. var closePath = options.closePath || false;
  33464. var invertUV = options.invertUV || false;
  33465. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33466. var offset = options.offset || defaultOffset;
  33467. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33468. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33469. var customUV = options.uvs;
  33470. var customColors = options.colors;
  33471. var positions = [];
  33472. var indices = [];
  33473. var normals = [];
  33474. var uvs = [];
  33475. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33476. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33477. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33478. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33479. var minlg; // minimal length among all paths from pathArray
  33480. var lg = []; // array of path lengths : nb of vertex per path
  33481. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33482. var p; // path iterator
  33483. var i; // point iterator
  33484. var j; // point iterator
  33485. // if single path in pathArray
  33486. if (pathArray.length < 2) {
  33487. var ar1 = [];
  33488. var ar2 = [];
  33489. for (i = 0; i < pathArray[0].length - offset; i++) {
  33490. ar1.push(pathArray[0][i]);
  33491. ar2.push(pathArray[0][i + offset]);
  33492. }
  33493. pathArray = [ar1, ar2];
  33494. }
  33495. // positions and horizontal distances (u)
  33496. var idc = 0;
  33497. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33498. var path;
  33499. var l;
  33500. minlg = pathArray[0].length;
  33501. var vectlg;
  33502. var dist;
  33503. for (p = 0; p < pathArray.length; p++) {
  33504. uTotalDistance[p] = 0;
  33505. us[p] = [0];
  33506. path = pathArray[p];
  33507. l = path.length;
  33508. minlg = (minlg < l) ? minlg : l;
  33509. j = 0;
  33510. while (j < l) {
  33511. positions.push(path[j].x, path[j].y, path[j].z);
  33512. if (j > 0) {
  33513. vectlg = path[j].subtract(path[j - 1]).length();
  33514. dist = vectlg + uTotalDistance[p];
  33515. us[p].push(dist);
  33516. uTotalDistance[p] = dist;
  33517. }
  33518. j++;
  33519. }
  33520. if (closePath) {
  33521. j--;
  33522. positions.push(path[0].x, path[0].y, path[0].z);
  33523. vectlg = path[j].subtract(path[0]).length();
  33524. dist = vectlg + uTotalDistance[p];
  33525. us[p].push(dist);
  33526. uTotalDistance[p] = dist;
  33527. }
  33528. lg[p] = l + closePathCorr;
  33529. idx[p] = idc;
  33530. idc += (l + closePathCorr);
  33531. }
  33532. // vertical distances (v)
  33533. var path1;
  33534. var path2;
  33535. var vertex1 = null;
  33536. var vertex2 = null;
  33537. for (i = 0; i < minlg + closePathCorr; i++) {
  33538. vTotalDistance[i] = 0;
  33539. vs[i] = [0];
  33540. for (p = 0; p < pathArray.length - 1; p++) {
  33541. path1 = pathArray[p];
  33542. path2 = pathArray[p + 1];
  33543. if (i === minlg) {
  33544. vertex1 = path1[0];
  33545. vertex2 = path2[0];
  33546. }
  33547. else {
  33548. vertex1 = path1[i];
  33549. vertex2 = path2[i];
  33550. }
  33551. vectlg = vertex2.subtract(vertex1).length();
  33552. dist = vectlg + vTotalDistance[i];
  33553. vs[i].push(dist);
  33554. vTotalDistance[i] = dist;
  33555. }
  33556. if (closeArray && vertex2 && vertex1) {
  33557. path1 = pathArray[p];
  33558. path2 = pathArray[0];
  33559. if (i === minlg) {
  33560. vertex2 = path2[0];
  33561. }
  33562. vectlg = vertex2.subtract(vertex1).length();
  33563. dist = vectlg + vTotalDistance[i];
  33564. vTotalDistance[i] = dist;
  33565. }
  33566. }
  33567. // uvs
  33568. var u;
  33569. var v;
  33570. if (customUV) {
  33571. for (p = 0; p < customUV.length; p++) {
  33572. uvs.push(customUV[p].x, customUV[p].y);
  33573. }
  33574. }
  33575. else {
  33576. for (p = 0; p < pathArray.length; p++) {
  33577. for (i = 0; i < minlg + closePathCorr; i++) {
  33578. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33579. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33580. if (invertUV) {
  33581. uvs.push(v, u);
  33582. }
  33583. else {
  33584. uvs.push(u, v);
  33585. }
  33586. }
  33587. }
  33588. }
  33589. // indices
  33590. p = 0; // path index
  33591. var pi = 0; // positions array index
  33592. var l1 = lg[p] - 1; // path1 length
  33593. var l2 = lg[p + 1] - 1; // path2 length
  33594. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33595. var shft = idx[1] - idx[0]; // shift
  33596. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33597. while (pi <= min && p < path1nb) {
  33598. // 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
  33599. indices.push(pi, pi + shft, pi + 1);
  33600. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33601. pi += 1;
  33602. if (pi === min) {
  33603. p++;
  33604. if (p === lg.length - 1) {
  33605. shft = idx[0] - idx[p];
  33606. l1 = lg[p] - 1;
  33607. l2 = lg[0] - 1;
  33608. }
  33609. else {
  33610. shft = idx[p + 1] - idx[p];
  33611. l1 = lg[p] - 1;
  33612. l2 = lg[p + 1] - 1;
  33613. }
  33614. pi = idx[p];
  33615. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33616. }
  33617. }
  33618. // normals
  33619. VertexData.ComputeNormals(positions, indices, normals);
  33620. if (closePath) {
  33621. var indexFirst = 0;
  33622. var indexLast = 0;
  33623. for (p = 0; p < pathArray.length; p++) {
  33624. indexFirst = idx[p] * 3;
  33625. if (p + 1 < pathArray.length) {
  33626. indexLast = (idx[p + 1] - 1) * 3;
  33627. }
  33628. else {
  33629. indexLast = normals.length - 3;
  33630. }
  33631. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33632. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33633. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33634. normals[indexLast] = normals[indexFirst];
  33635. normals[indexLast + 1] = normals[indexFirst + 1];
  33636. normals[indexLast + 2] = normals[indexFirst + 2];
  33637. }
  33638. }
  33639. // sides
  33640. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33641. // Colors
  33642. var colors = null;
  33643. if (customColors) {
  33644. colors = new Float32Array(customColors.length * 4);
  33645. for (var c = 0; c < customColors.length; c++) {
  33646. colors[c * 4] = customColors[c].r;
  33647. colors[c * 4 + 1] = customColors[c].g;
  33648. colors[c * 4 + 2] = customColors[c].b;
  33649. colors[c * 4 + 3] = customColors[c].a;
  33650. }
  33651. }
  33652. // Result
  33653. var vertexData = new VertexData();
  33654. var positions32 = new Float32Array(positions);
  33655. var normals32 = new Float32Array(normals);
  33656. var uvs32 = new Float32Array(uvs);
  33657. vertexData.indices = indices;
  33658. vertexData.positions = positions32;
  33659. vertexData.normals = normals32;
  33660. vertexData.uvs = uvs32;
  33661. if (colors) {
  33662. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33663. }
  33664. if (closePath) {
  33665. vertexData._idx = idx;
  33666. }
  33667. return vertexData;
  33668. };
  33669. /**
  33670. * Creates the VertexData of the Box.
  33671. */
  33672. VertexData.CreateBox = function (options) {
  33673. var normalsSource = [
  33674. new BABYLON.Vector3(0, 0, 1),
  33675. new BABYLON.Vector3(0, 0, -1),
  33676. new BABYLON.Vector3(1, 0, 0),
  33677. new BABYLON.Vector3(-1, 0, 0),
  33678. new BABYLON.Vector3(0, 1, 0),
  33679. new BABYLON.Vector3(0, -1, 0)
  33680. ];
  33681. var indices = [];
  33682. var positions = [];
  33683. var normals = [];
  33684. var uvs = [];
  33685. var width = options.width || options.size || 1;
  33686. var height = options.height || options.size || 1;
  33687. var depth = options.depth || options.size || 1;
  33688. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33689. var faceUV = options.faceUV || new Array(6);
  33690. var faceColors = options.faceColors;
  33691. var colors = [];
  33692. // default face colors and UV if undefined
  33693. for (var f = 0; f < 6; f++) {
  33694. if (faceUV[f] === undefined) {
  33695. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33696. }
  33697. if (faceColors && faceColors[f] === undefined) {
  33698. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33699. }
  33700. }
  33701. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33702. // Create each face in turn.
  33703. for (var index = 0; index < normalsSource.length; index++) {
  33704. var normal = normalsSource[index];
  33705. // Get two vectors perpendicular to the face normal and to each other.
  33706. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33707. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33708. // Six indices (two triangles) per face.
  33709. var verticesLength = positions.length / 3;
  33710. indices.push(verticesLength);
  33711. indices.push(verticesLength + 1);
  33712. indices.push(verticesLength + 2);
  33713. indices.push(verticesLength);
  33714. indices.push(verticesLength + 2);
  33715. indices.push(verticesLength + 3);
  33716. // Four vertices per face.
  33717. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33718. positions.push(vertex.x, vertex.y, vertex.z);
  33719. normals.push(normal.x, normal.y, normal.z);
  33720. uvs.push(faceUV[index].z, faceUV[index].w);
  33721. if (faceColors) {
  33722. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33723. }
  33724. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33725. positions.push(vertex.x, vertex.y, vertex.z);
  33726. normals.push(normal.x, normal.y, normal.z);
  33727. uvs.push(faceUV[index].x, faceUV[index].w);
  33728. if (faceColors) {
  33729. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33730. }
  33731. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33732. positions.push(vertex.x, vertex.y, vertex.z);
  33733. normals.push(normal.x, normal.y, normal.z);
  33734. uvs.push(faceUV[index].x, faceUV[index].y);
  33735. if (faceColors) {
  33736. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33737. }
  33738. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33739. positions.push(vertex.x, vertex.y, vertex.z);
  33740. normals.push(normal.x, normal.y, normal.z);
  33741. uvs.push(faceUV[index].z, faceUV[index].y);
  33742. if (faceColors) {
  33743. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33744. }
  33745. }
  33746. // sides
  33747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33748. // Result
  33749. var vertexData = new VertexData();
  33750. vertexData.indices = indices;
  33751. vertexData.positions = positions;
  33752. vertexData.normals = normals;
  33753. vertexData.uvs = uvs;
  33754. if (faceColors) {
  33755. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33756. vertexData.colors = totalColors;
  33757. }
  33758. return vertexData;
  33759. };
  33760. /**
  33761. * Creates the VertexData of the Sphere.
  33762. */
  33763. VertexData.CreateSphere = function (options) {
  33764. var segments = options.segments || 32;
  33765. var diameterX = options.diameterX || options.diameter || 1;
  33766. var diameterY = options.diameterY || options.diameter || 1;
  33767. var diameterZ = options.diameterZ || options.diameter || 1;
  33768. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33769. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33770. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33771. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33772. var totalZRotationSteps = 2 + segments;
  33773. var totalYRotationSteps = 2 * totalZRotationSteps;
  33774. var indices = [];
  33775. var positions = [];
  33776. var normals = [];
  33777. var uvs = [];
  33778. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33779. var normalizedZ = zRotationStep / totalZRotationSteps;
  33780. var angleZ = normalizedZ * Math.PI * slice;
  33781. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33782. var normalizedY = yRotationStep / totalYRotationSteps;
  33783. var angleY = normalizedY * Math.PI * 2 * arc;
  33784. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33785. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33786. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33787. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33788. var vertex = complete.multiply(radius);
  33789. var normal = complete.divide(radius).normalize();
  33790. positions.push(vertex.x, vertex.y, vertex.z);
  33791. normals.push(normal.x, normal.y, normal.z);
  33792. uvs.push(normalizedY, normalizedZ);
  33793. }
  33794. if (zRotationStep > 0) {
  33795. var verticesCount = positions.length / 3;
  33796. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33797. indices.push((firstIndex));
  33798. indices.push((firstIndex + 1));
  33799. indices.push(firstIndex + totalYRotationSteps + 1);
  33800. indices.push((firstIndex + totalYRotationSteps + 1));
  33801. indices.push((firstIndex + 1));
  33802. indices.push((firstIndex + totalYRotationSteps + 2));
  33803. }
  33804. }
  33805. }
  33806. // Sides
  33807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33808. // Result
  33809. var vertexData = new VertexData();
  33810. vertexData.indices = indices;
  33811. vertexData.positions = positions;
  33812. vertexData.normals = normals;
  33813. vertexData.uvs = uvs;
  33814. return vertexData;
  33815. };
  33816. /**
  33817. * Creates the VertexData of the Cylinder or Cone.
  33818. */
  33819. VertexData.CreateCylinder = function (options) {
  33820. var height = options.height || 2;
  33821. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33822. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33823. var tessellation = options.tessellation || 24;
  33824. var subdivisions = options.subdivisions || 1;
  33825. var hasRings = options.hasRings ? true : false;
  33826. var enclose = options.enclose ? true : false;
  33827. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33828. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33829. var faceUV = options.faceUV || new Array(3);
  33830. var faceColors = options.faceColors;
  33831. // default face colors and UV if undefined
  33832. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33833. var ringNb = (hasRings) ? subdivisions : 1;
  33834. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33835. var f;
  33836. for (f = 0; f < surfaceNb; f++) {
  33837. if (faceColors && faceColors[f] === undefined) {
  33838. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33839. }
  33840. }
  33841. for (f = 0; f < surfaceNb; f++) {
  33842. if (faceUV && faceUV[f] === undefined) {
  33843. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33844. }
  33845. }
  33846. var indices = new Array();
  33847. var positions = new Array();
  33848. var normals = new Array();
  33849. var uvs = new Array();
  33850. var colors = new Array();
  33851. var angle_step = Math.PI * 2 * arc / tessellation;
  33852. var angle;
  33853. var h;
  33854. var radius;
  33855. var tan = (diameterBottom - diameterTop) / 2 / height;
  33856. var ringVertex = BABYLON.Vector3.Zero();
  33857. var ringNormal = BABYLON.Vector3.Zero();
  33858. var ringFirstVertex = BABYLON.Vector3.Zero();
  33859. var ringFirstNormal = BABYLON.Vector3.Zero();
  33860. var quadNormal = BABYLON.Vector3.Zero();
  33861. var Y = BABYLON.Axis.Y;
  33862. // positions, normals, uvs
  33863. var i;
  33864. var j;
  33865. var r;
  33866. var ringIdx = 1;
  33867. var s = 1; // surface index
  33868. var cs = 0;
  33869. var v = 0;
  33870. for (i = 0; i <= subdivisions; i++) {
  33871. h = i / subdivisions;
  33872. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33873. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33874. for (r = 0; r < ringIdx; r++) {
  33875. if (hasRings) {
  33876. s += r;
  33877. }
  33878. if (enclose) {
  33879. s += 2 * r;
  33880. }
  33881. for (j = 0; j <= tessellation; j++) {
  33882. angle = j * angle_step;
  33883. // position
  33884. ringVertex.x = Math.cos(-angle) * radius;
  33885. ringVertex.y = -height / 2 + h * height;
  33886. ringVertex.z = Math.sin(-angle) * radius;
  33887. // normal
  33888. if (diameterTop === 0 && i === subdivisions) {
  33889. // if no top cap, reuse former normals
  33890. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33891. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33892. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33893. }
  33894. else {
  33895. ringNormal.x = ringVertex.x;
  33896. ringNormal.z = ringVertex.z;
  33897. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33898. ringNormal.normalize();
  33899. }
  33900. // keep first ring vertex values for enclose
  33901. if (j === 0) {
  33902. ringFirstVertex.copyFrom(ringVertex);
  33903. ringFirstNormal.copyFrom(ringNormal);
  33904. }
  33905. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33906. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33907. if (hasRings) {
  33908. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33909. }
  33910. else {
  33911. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33912. }
  33913. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33914. if (faceColors) {
  33915. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33916. }
  33917. }
  33918. // if enclose, add four vertices and their dedicated normals
  33919. if (arc !== 1 && enclose) {
  33920. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33921. positions.push(0, ringVertex.y, 0);
  33922. positions.push(0, ringVertex.y, 0);
  33923. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33924. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33925. quadNormal.normalize();
  33926. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33927. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33928. quadNormal.normalize();
  33929. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33930. if (hasRings) {
  33931. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33932. }
  33933. else {
  33934. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33935. }
  33936. uvs.push(faceUV[s + 1].x, v);
  33937. uvs.push(faceUV[s + 1].z, v);
  33938. if (hasRings) {
  33939. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33940. }
  33941. else {
  33942. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33943. }
  33944. uvs.push(faceUV[s + 2].x, v);
  33945. uvs.push(faceUV[s + 2].z, v);
  33946. if (faceColors) {
  33947. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33948. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33949. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33950. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33951. }
  33952. }
  33953. if (cs !== s) {
  33954. cs = s;
  33955. }
  33956. }
  33957. }
  33958. // indices
  33959. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33960. var s;
  33961. i = 0;
  33962. for (s = 0; s < subdivisions; s++) {
  33963. var i0 = 0;
  33964. var i1 = 0;
  33965. var i2 = 0;
  33966. var i3 = 0;
  33967. for (j = 0; j < tessellation; j++) {
  33968. i0 = i * (e + 1) + j;
  33969. i1 = (i + 1) * (e + 1) + j;
  33970. i2 = i * (e + 1) + (j + 1);
  33971. i3 = (i + 1) * (e + 1) + (j + 1);
  33972. indices.push(i0, i1, i2);
  33973. indices.push(i3, i2, i1);
  33974. }
  33975. if (arc !== 1 && enclose) {
  33976. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33977. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33978. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33979. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33980. }
  33981. i = (hasRings) ? (i + 2) : (i + 1);
  33982. }
  33983. // Caps
  33984. var createCylinderCap = function (isTop) {
  33985. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33986. if (radius === 0) {
  33987. return;
  33988. }
  33989. // Cap positions, normals & uvs
  33990. var angle;
  33991. var circleVector;
  33992. var i;
  33993. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33994. var c = null;
  33995. if (faceColors) {
  33996. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33997. }
  33998. // cap center
  33999. var vbase = positions.length / 3;
  34000. var offset = isTop ? height / 2 : -height / 2;
  34001. var center = new BABYLON.Vector3(0, offset, 0);
  34002. positions.push(center.x, center.y, center.z);
  34003. normals.push(0, isTop ? 1 : -1, 0);
  34004. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  34005. if (c) {
  34006. colors.push(c.r, c.g, c.b, c.a);
  34007. }
  34008. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  34009. for (i = 0; i <= tessellation; i++) {
  34010. angle = Math.PI * 2 * i * arc / tessellation;
  34011. var cos = Math.cos(-angle);
  34012. var sin = Math.sin(-angle);
  34013. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  34014. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  34015. positions.push(circleVector.x, circleVector.y, circleVector.z);
  34016. normals.push(0, isTop ? 1 : -1, 0);
  34017. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34018. if (c) {
  34019. colors.push(c.r, c.g, c.b, c.a);
  34020. }
  34021. }
  34022. // Cap indices
  34023. for (i = 0; i < tessellation; i++) {
  34024. if (!isTop) {
  34025. indices.push(vbase);
  34026. indices.push(vbase + (i + 1));
  34027. indices.push(vbase + (i + 2));
  34028. }
  34029. else {
  34030. indices.push(vbase);
  34031. indices.push(vbase + (i + 2));
  34032. indices.push(vbase + (i + 1));
  34033. }
  34034. }
  34035. };
  34036. // add caps to geometry
  34037. createCylinderCap(false);
  34038. createCylinderCap(true);
  34039. // Sides
  34040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34041. var vertexData = new VertexData();
  34042. vertexData.indices = indices;
  34043. vertexData.positions = positions;
  34044. vertexData.normals = normals;
  34045. vertexData.uvs = uvs;
  34046. if (faceColors) {
  34047. vertexData.colors = colors;
  34048. }
  34049. return vertexData;
  34050. };
  34051. /**
  34052. * Creates the VertexData of the Torus.
  34053. */
  34054. VertexData.CreateTorus = function (options) {
  34055. var indices = [];
  34056. var positions = [];
  34057. var normals = [];
  34058. var uvs = [];
  34059. var diameter = options.diameter || 1;
  34060. var thickness = options.thickness || 0.5;
  34061. var tessellation = options.tessellation || 16;
  34062. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34063. var stride = tessellation + 1;
  34064. for (var i = 0; i <= tessellation; i++) {
  34065. var u = i / tessellation;
  34066. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34067. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34068. for (var j = 0; j <= tessellation; j++) {
  34069. var v = 1 - j / tessellation;
  34070. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34071. var dx = Math.cos(innerAngle);
  34072. var dy = Math.sin(innerAngle);
  34073. // Create a vertex.
  34074. var normal = new BABYLON.Vector3(dx, dy, 0);
  34075. var position = normal.scale(thickness / 2);
  34076. var textureCoordinate = new BABYLON.Vector2(u, v);
  34077. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34078. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34079. positions.push(position.x, position.y, position.z);
  34080. normals.push(normal.x, normal.y, normal.z);
  34081. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34082. // And create indices for two triangles.
  34083. var nextI = (i + 1) % stride;
  34084. var nextJ = (j + 1) % stride;
  34085. indices.push(i * stride + j);
  34086. indices.push(i * stride + nextJ);
  34087. indices.push(nextI * stride + j);
  34088. indices.push(i * stride + nextJ);
  34089. indices.push(nextI * stride + nextJ);
  34090. indices.push(nextI * stride + j);
  34091. }
  34092. }
  34093. // Sides
  34094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34095. // Result
  34096. var vertexData = new VertexData();
  34097. vertexData.indices = indices;
  34098. vertexData.positions = positions;
  34099. vertexData.normals = normals;
  34100. vertexData.uvs = uvs;
  34101. return vertexData;
  34102. };
  34103. /**
  34104. * Creates the VertexData of the LineSystem.
  34105. */
  34106. VertexData.CreateLineSystem = function (options) {
  34107. var indices = [];
  34108. var positions = [];
  34109. var lines = options.lines;
  34110. var colors = options.colors;
  34111. var vertexColors = [];
  34112. var idx = 0;
  34113. for (var l = 0; l < lines.length; l++) {
  34114. var points = lines[l];
  34115. for (var index = 0; index < points.length; index++) {
  34116. positions.push(points[index].x, points[index].y, points[index].z);
  34117. if (colors) {
  34118. var color = colors[l];
  34119. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34120. }
  34121. if (index > 0) {
  34122. indices.push(idx - 1);
  34123. indices.push(idx);
  34124. }
  34125. idx++;
  34126. }
  34127. }
  34128. var vertexData = new VertexData();
  34129. vertexData.indices = indices;
  34130. vertexData.positions = positions;
  34131. if (colors) {
  34132. vertexData.colors = vertexColors;
  34133. }
  34134. return vertexData;
  34135. };
  34136. /**
  34137. * Create the VertexData of the DashedLines.
  34138. */
  34139. VertexData.CreateDashedLines = function (options) {
  34140. var dashSize = options.dashSize || 3;
  34141. var gapSize = options.gapSize || 1;
  34142. var dashNb = options.dashNb || 200;
  34143. var points = options.points;
  34144. var positions = new Array();
  34145. var indices = new Array();
  34146. var curvect = BABYLON.Vector3.Zero();
  34147. var lg = 0;
  34148. var nb = 0;
  34149. var shft = 0;
  34150. var dashshft = 0;
  34151. var curshft = 0;
  34152. var idx = 0;
  34153. var i = 0;
  34154. for (i = 0; i < points.length - 1; i++) {
  34155. points[i + 1].subtractToRef(points[i], curvect);
  34156. lg += curvect.length();
  34157. }
  34158. shft = lg / dashNb;
  34159. dashshft = dashSize * shft / (dashSize + gapSize);
  34160. for (i = 0; i < points.length - 1; i++) {
  34161. points[i + 1].subtractToRef(points[i], curvect);
  34162. nb = Math.floor(curvect.length() / shft);
  34163. curvect.normalize();
  34164. for (var j = 0; j < nb; j++) {
  34165. curshft = shft * j;
  34166. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34167. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34168. indices.push(idx, idx + 1);
  34169. idx += 2;
  34170. }
  34171. }
  34172. // Result
  34173. var vertexData = new VertexData();
  34174. vertexData.positions = positions;
  34175. vertexData.indices = indices;
  34176. return vertexData;
  34177. };
  34178. /**
  34179. * Creates the VertexData of the Ground.
  34180. */
  34181. VertexData.CreateGround = function (options) {
  34182. var indices = [];
  34183. var positions = [];
  34184. var normals = [];
  34185. var uvs = [];
  34186. var row, col;
  34187. var width = options.width || 1;
  34188. var height = options.height || 1;
  34189. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34190. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34191. for (row = 0; row <= subdivisionsY; row++) {
  34192. for (col = 0; col <= subdivisionsX; col++) {
  34193. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34194. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34195. positions.push(position.x, position.y, position.z);
  34196. normals.push(normal.x, normal.y, normal.z);
  34197. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34198. }
  34199. }
  34200. for (row = 0; row < subdivisionsY; row++) {
  34201. for (col = 0; col < subdivisionsX; col++) {
  34202. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34203. indices.push(col + 1 + row * (subdivisionsX + 1));
  34204. indices.push(col + row * (subdivisionsX + 1));
  34205. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34206. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34207. indices.push(col + row * (subdivisionsX + 1));
  34208. }
  34209. }
  34210. // Result
  34211. var vertexData = new VertexData();
  34212. vertexData.indices = indices;
  34213. vertexData.positions = positions;
  34214. vertexData.normals = normals;
  34215. vertexData.uvs = uvs;
  34216. return vertexData;
  34217. };
  34218. /**
  34219. * Creates the VertexData of the TiledGround.
  34220. */
  34221. VertexData.CreateTiledGround = function (options) {
  34222. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34223. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34224. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34225. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34226. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34227. var precision = options.precision || { w: 1, h: 1 };
  34228. var indices = new Array();
  34229. var positions = new Array();
  34230. var normals = new Array();
  34231. var uvs = new Array();
  34232. var row, col, tileRow, tileCol;
  34233. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34234. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34235. precision.w = (precision.w < 1) ? 1 : precision.w;
  34236. precision.h = (precision.h < 1) ? 1 : precision.h;
  34237. var tileSize = {
  34238. 'w': (xmax - xmin) / subdivisions.w,
  34239. 'h': (zmax - zmin) / subdivisions.h
  34240. };
  34241. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34242. // Indices
  34243. var base = positions.length / 3;
  34244. var rowLength = precision.w + 1;
  34245. for (row = 0; row < precision.h; row++) {
  34246. for (col = 0; col < precision.w; col++) {
  34247. var square = [
  34248. base + col + row * rowLength,
  34249. base + (col + 1) + row * rowLength,
  34250. base + (col + 1) + (row + 1) * rowLength,
  34251. base + col + (row + 1) * rowLength
  34252. ];
  34253. indices.push(square[1]);
  34254. indices.push(square[2]);
  34255. indices.push(square[3]);
  34256. indices.push(square[0]);
  34257. indices.push(square[1]);
  34258. indices.push(square[3]);
  34259. }
  34260. }
  34261. // Position, normals and uvs
  34262. var position = BABYLON.Vector3.Zero();
  34263. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34264. for (row = 0; row <= precision.h; row++) {
  34265. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34266. for (col = 0; col <= precision.w; col++) {
  34267. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34268. position.y = 0;
  34269. positions.push(position.x, position.y, position.z);
  34270. normals.push(normal.x, normal.y, normal.z);
  34271. uvs.push(col / precision.w, row / precision.h);
  34272. }
  34273. }
  34274. }
  34275. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34276. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34277. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34278. }
  34279. }
  34280. // Result
  34281. var vertexData = new VertexData();
  34282. vertexData.indices = indices;
  34283. vertexData.positions = positions;
  34284. vertexData.normals = normals;
  34285. vertexData.uvs = uvs;
  34286. return vertexData;
  34287. };
  34288. /**
  34289. * Creates the VertexData of the Ground designed from a heightmap.
  34290. */
  34291. VertexData.CreateGroundFromHeightMap = function (options) {
  34292. var indices = [];
  34293. var positions = [];
  34294. var normals = [];
  34295. var uvs = [];
  34296. var row, col;
  34297. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34298. // Vertices
  34299. for (row = 0; row <= options.subdivisions; row++) {
  34300. for (col = 0; col <= options.subdivisions; col++) {
  34301. 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));
  34302. // Compute height
  34303. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34304. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34305. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34306. var r = options.buffer[pos] / 255.0;
  34307. var g = options.buffer[pos + 1] / 255.0;
  34308. var b = options.buffer[pos + 2] / 255.0;
  34309. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34310. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34311. // Add vertex
  34312. positions.push(position.x, position.y, position.z);
  34313. normals.push(0, 0, 0);
  34314. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34315. }
  34316. }
  34317. // Indices
  34318. for (row = 0; row < options.subdivisions; row++) {
  34319. for (col = 0; col < options.subdivisions; col++) {
  34320. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34321. indices.push(col + 1 + row * (options.subdivisions + 1));
  34322. indices.push(col + row * (options.subdivisions + 1));
  34323. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34324. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34325. indices.push(col + row * (options.subdivisions + 1));
  34326. }
  34327. }
  34328. // Normals
  34329. VertexData.ComputeNormals(positions, indices, normals);
  34330. // Result
  34331. var vertexData = new VertexData();
  34332. vertexData.indices = indices;
  34333. vertexData.positions = positions;
  34334. vertexData.normals = normals;
  34335. vertexData.uvs = uvs;
  34336. return vertexData;
  34337. };
  34338. /**
  34339. * Creates the VertexData of the Plane.
  34340. */
  34341. VertexData.CreatePlane = function (options) {
  34342. var indices = [];
  34343. var positions = [];
  34344. var normals = [];
  34345. var uvs = [];
  34346. var width = options.width || options.size || 1;
  34347. var height = options.height || options.size || 1;
  34348. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34349. // Vertices
  34350. var halfWidth = width / 2.0;
  34351. var halfHeight = height / 2.0;
  34352. positions.push(-halfWidth, -halfHeight, 0);
  34353. normals.push(0, 0, -1.0);
  34354. uvs.push(0.0, 0.0);
  34355. positions.push(halfWidth, -halfHeight, 0);
  34356. normals.push(0, 0, -1.0);
  34357. uvs.push(1.0, 0.0);
  34358. positions.push(halfWidth, halfHeight, 0);
  34359. normals.push(0, 0, -1.0);
  34360. uvs.push(1.0, 1.0);
  34361. positions.push(-halfWidth, halfHeight, 0);
  34362. normals.push(0, 0, -1.0);
  34363. uvs.push(0.0, 1.0);
  34364. // Indices
  34365. indices.push(0);
  34366. indices.push(1);
  34367. indices.push(2);
  34368. indices.push(0);
  34369. indices.push(2);
  34370. indices.push(3);
  34371. // Sides
  34372. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34373. // Result
  34374. var vertexData = new VertexData();
  34375. vertexData.indices = indices;
  34376. vertexData.positions = positions;
  34377. vertexData.normals = normals;
  34378. vertexData.uvs = uvs;
  34379. return vertexData;
  34380. };
  34381. /**
  34382. * Creates the VertexData of the Disc or regular Polygon.
  34383. */
  34384. VertexData.CreateDisc = function (options) {
  34385. var positions = new Array();
  34386. var indices = new Array();
  34387. var normals = new Array();
  34388. var uvs = new Array();
  34389. var radius = options.radius || 0.5;
  34390. var tessellation = options.tessellation || 64;
  34391. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34392. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34393. // positions and uvs
  34394. positions.push(0, 0, 0); // disc center first
  34395. uvs.push(0.5, 0.5);
  34396. var theta = Math.PI * 2 * arc;
  34397. var step = theta / tessellation;
  34398. for (var a = 0; a < theta; a += step) {
  34399. var x = Math.cos(a);
  34400. var y = Math.sin(a);
  34401. var u = (x + 1) / 2;
  34402. var v = (1 - y) / 2;
  34403. positions.push(radius * x, radius * y, 0);
  34404. uvs.push(u, v);
  34405. }
  34406. if (arc === 1) {
  34407. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34408. uvs.push(uvs[2], uvs[3]);
  34409. }
  34410. //indices
  34411. var vertexNb = positions.length / 3;
  34412. for (var i = 1; i < vertexNb - 1; i++) {
  34413. indices.push(i + 1, 0, i);
  34414. }
  34415. // result
  34416. VertexData.ComputeNormals(positions, indices, normals);
  34417. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34418. var vertexData = new VertexData();
  34419. vertexData.indices = indices;
  34420. vertexData.positions = positions;
  34421. vertexData.normals = normals;
  34422. vertexData.uvs = uvs;
  34423. return vertexData;
  34424. };
  34425. /**
  34426. * Re-creates the VertexData of the Polygon for sideOrientation.
  34427. */
  34428. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34429. var faceUV = fUV || new Array(3);
  34430. var faceColors = fColors;
  34431. var colors = [];
  34432. // default face colors and UV if undefined
  34433. for (var f = 0; f < 3; f++) {
  34434. if (faceUV[f] === undefined) {
  34435. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34436. }
  34437. if (faceColors && faceColors[f] === undefined) {
  34438. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34439. }
  34440. }
  34441. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34442. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34443. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34444. var indices = polygon.getIndices();
  34445. // set face colours and textures
  34446. var idx = 0;
  34447. var face = 0;
  34448. for (var index = 0; index < normals.length; index += 3) {
  34449. //Edge Face no. 1
  34450. if (Math.abs(normals[index + 1]) < 0.001) {
  34451. face = 1;
  34452. }
  34453. //Top Face no. 0
  34454. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34455. face = 0;
  34456. }
  34457. //Bottom Face no. 2
  34458. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34459. face = 2;
  34460. }
  34461. idx = index / 3;
  34462. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34463. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34464. if (faceColors) {
  34465. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34466. }
  34467. }
  34468. // sides
  34469. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34470. // Result
  34471. var vertexData = new VertexData();
  34472. vertexData.indices = indices;
  34473. vertexData.positions = positions;
  34474. vertexData.normals = normals;
  34475. vertexData.uvs = uvs;
  34476. if (faceColors) {
  34477. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34478. vertexData.colors = totalColors;
  34479. }
  34480. return vertexData;
  34481. };
  34482. /**
  34483. * Creates the VertexData of the IcoSphere.
  34484. */
  34485. VertexData.CreateIcoSphere = function (options) {
  34486. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34487. var radius = options.radius || 1;
  34488. var flat = (options.flat === undefined) ? true : options.flat;
  34489. var subdivisions = options.subdivisions || 4;
  34490. var radiusX = options.radiusX || radius;
  34491. var radiusY = options.radiusY || radius;
  34492. var radiusZ = options.radiusZ || radius;
  34493. var t = (1 + Math.sqrt(5)) / 2;
  34494. // 12 vertex x,y,z
  34495. var ico_vertices = [
  34496. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34497. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34498. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34499. ];
  34500. // index of 3 vertex makes a face of icopshere
  34501. var ico_indices = [
  34502. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34503. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34504. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34505. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34506. ];
  34507. // vertex for uv have aliased position, not for UV
  34508. var vertices_unalias_id = [
  34509. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34510. // vertex alias
  34511. 0,
  34512. 2,
  34513. 3,
  34514. 3,
  34515. 3,
  34516. 4,
  34517. 7,
  34518. 8,
  34519. 9,
  34520. 9,
  34521. 10,
  34522. 11 // 23: B + 12
  34523. ];
  34524. // uv as integer step (not pixels !)
  34525. var ico_vertexuv = [
  34526. 5, 1, 3, 1, 6, 4, 0, 0,
  34527. 5, 3, 4, 2, 2, 2, 4, 0,
  34528. 2, 0, 1, 1, 6, 0, 6, 2,
  34529. // vertex alias (for same vertex on different faces)
  34530. 0, 4,
  34531. 3, 3,
  34532. 4, 4,
  34533. 3, 1,
  34534. 4, 2,
  34535. 4, 4,
  34536. 0, 2,
  34537. 1, 1,
  34538. 2, 2,
  34539. 3, 3,
  34540. 1, 3,
  34541. 2, 4 // 23: B + 12
  34542. ];
  34543. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34544. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34545. // First island of uv mapping
  34546. // v = 4h 3+ 2
  34547. // v = 3h 9+ 4
  34548. // v = 2h 9+ 5 B
  34549. // v = 1h 9 1 0
  34550. // v = 0h 3 8 7 A
  34551. // u = 0 1 2 3 4 5 6 *a
  34552. // Second island of uv mapping
  34553. // v = 4h 0+ B+ 4+
  34554. // v = 3h A+ 2+
  34555. // v = 2h 7+ 6 3+
  34556. // v = 1h 8+ 3+
  34557. // v = 0h
  34558. // u = 0 1 2 3 4 5 6 *a
  34559. // Face layout on texture UV mapping
  34560. // ============
  34561. // \ 4 /\ 16 / ======
  34562. // \ / \ / /\ 11 /
  34563. // \/ 7 \/ / \ /
  34564. // ======= / 10 \/
  34565. // /\ 17 /\ =======
  34566. // / \ / \ \ 15 /\
  34567. // / 8 \/ 12 \ \ / \
  34568. // ============ \/ 6 \
  34569. // \ 18 /\ ============
  34570. // \ / \ \ 5 /\ 0 /
  34571. // \/ 13 \ \ / \ /
  34572. // ======= \/ 1 \/
  34573. // =============
  34574. // /\ 19 /\ 2 /\
  34575. // / \ / \ / \
  34576. // / 14 \/ 9 \/ 3 \
  34577. // ===================
  34578. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34579. var ustep = 138 / 1024;
  34580. var vstep = 239 / 1024;
  34581. var uoffset = 60 / 1024;
  34582. var voffset = 26 / 1024;
  34583. // Second island should have margin, not to touch the first island
  34584. // avoid any borderline artefact in pixel rounding
  34585. var island_u_offset = -40 / 1024;
  34586. var island_v_offset = +20 / 1024;
  34587. // face is either island 0 or 1 :
  34588. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34589. var island = [
  34590. 0, 0, 0, 0, 1,
  34591. 0, 0, 1, 1, 0,
  34592. 0, 0, 1, 1, 0,
  34593. 0, 1, 1, 1, 0 // 15 - 19
  34594. ];
  34595. var indices = new Array();
  34596. var positions = new Array();
  34597. var normals = new Array();
  34598. var uvs = new Array();
  34599. var current_indice = 0;
  34600. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34601. var face_vertex_pos = new Array(3);
  34602. var face_vertex_uv = new Array(3);
  34603. var v012;
  34604. for (v012 = 0; v012 < 3; v012++) {
  34605. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34606. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34607. }
  34608. // create all with normals
  34609. for (var face = 0; face < 20; face++) {
  34610. // 3 vertex per face
  34611. for (v012 = 0; v012 < 3; v012++) {
  34612. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34613. var v_id = ico_indices[3 * face + v012];
  34614. // vertex have 3D position (x,y,z)
  34615. 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]);
  34616. // Normalize to get normal, then scale to radius
  34617. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34618. // uv Coordinates from vertex ID
  34619. 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);
  34620. }
  34621. // Subdivide the face (interpolate pos, norm, uv)
  34622. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34623. // - norm is linear interpolation of vertex corner normal
  34624. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34625. // - uv is linear interpolation
  34626. //
  34627. // Topology is as below for sub-divide by 2
  34628. // vertex shown as v0,v1,v2
  34629. // interp index is i1 to progress in range [v0,v1[
  34630. // interp index is i2 to progress in range [v0,v2[
  34631. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34632. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34633. //
  34634. //
  34635. // i2 v2
  34636. // ^ ^
  34637. // / / \
  34638. // / / \
  34639. // / / \
  34640. // / / (0,1) \
  34641. // / #---------\
  34642. // / / \ (0,0)'/ \
  34643. // / / \ / \
  34644. // / / \ / \
  34645. // / / (0,0) \ / (1,0) \
  34646. // / #---------#---------\
  34647. // v0 v1
  34648. //
  34649. // --------------------> i1
  34650. //
  34651. // interp of (i1,i2):
  34652. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34653. // along i1 : lerp(x0,x1, i1/(S-i2))
  34654. //
  34655. // centroid of triangle is needed to get help normal computation
  34656. // (c1,c2) are used for centroid location
  34657. var interp_vertex = function (i1, i2, c1, c2) {
  34658. // vertex is interpolated from
  34659. // - face_vertex_pos[0..2]
  34660. // - face_vertex_uv[0..2]
  34661. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34662. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34663. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34664. pos_interp.normalize();
  34665. var vertex_normal;
  34666. if (flat) {
  34667. // in flat mode, recalculate normal as face centroid normal
  34668. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34669. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34670. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34671. }
  34672. else {
  34673. // in smooth mode, recalculate normal from each single vertex position
  34674. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34675. }
  34676. // Vertex normal need correction due to X,Y,Z radius scaling
  34677. vertex_normal.x /= radiusX;
  34678. vertex_normal.y /= radiusY;
  34679. vertex_normal.z /= radiusZ;
  34680. vertex_normal.normalize();
  34681. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34682. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34683. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34684. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34685. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34686. uvs.push(uv_interp.x, uv_interp.y);
  34687. // push each vertex has member of a face
  34688. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34689. indices.push(current_indice);
  34690. current_indice++;
  34691. };
  34692. for (var i2 = 0; i2 < subdivisions; i2++) {
  34693. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34694. // face : (i1,i2) for /\ :
  34695. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34696. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34697. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34698. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34699. if (i1 + i2 + 1 < subdivisions) {
  34700. // face : (i1,i2)' for \/ :
  34701. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34702. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34703. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34704. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34705. }
  34706. }
  34707. }
  34708. }
  34709. // Sides
  34710. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34711. // Result
  34712. var vertexData = new VertexData();
  34713. vertexData.indices = indices;
  34714. vertexData.positions = positions;
  34715. vertexData.normals = normals;
  34716. vertexData.uvs = uvs;
  34717. return vertexData;
  34718. };
  34719. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34720. /**
  34721. * Creates the VertexData of the Polyhedron.
  34722. */
  34723. VertexData.CreatePolyhedron = function (options) {
  34724. // provided polyhedron types :
  34725. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34726. // 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)
  34727. var polyhedra = [];
  34728. 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]] };
  34729. 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]] };
  34730. polyhedra[2] = {
  34731. 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]],
  34732. 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]]
  34733. };
  34734. polyhedra[3] = {
  34735. 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]],
  34736. 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]]
  34737. };
  34738. polyhedra[4] = {
  34739. 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]],
  34740. 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]]
  34741. };
  34742. 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]] };
  34743. 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]] };
  34744. 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]] };
  34745. 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]] };
  34746. 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]] };
  34747. 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]] };
  34748. 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]] };
  34749. 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]] };
  34750. 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]] };
  34751. polyhedra[14] = {
  34752. 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]],
  34753. 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]]
  34754. };
  34755. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34756. var size = options.size;
  34757. var sizeX = options.sizeX || size || 1;
  34758. var sizeY = options.sizeY || size || 1;
  34759. var sizeZ = options.sizeZ || size || 1;
  34760. var data = options.custom || polyhedra[type];
  34761. var nbfaces = data.face.length;
  34762. var faceUV = options.faceUV || new Array(nbfaces);
  34763. var faceColors = options.faceColors;
  34764. var flat = (options.flat === undefined) ? true : options.flat;
  34765. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34766. var positions = new Array();
  34767. var indices = new Array();
  34768. var normals = new Array();
  34769. var uvs = new Array();
  34770. var colors = new Array();
  34771. var index = 0;
  34772. var faceIdx = 0; // face cursor in the array "indexes"
  34773. var indexes = new Array();
  34774. var i = 0;
  34775. var f = 0;
  34776. var u, v, ang, x, y, tmp;
  34777. // default face colors and UV if undefined
  34778. if (flat) {
  34779. for (f = 0; f < nbfaces; f++) {
  34780. if (faceColors && faceColors[f] === undefined) {
  34781. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34782. }
  34783. if (faceUV && faceUV[f] === undefined) {
  34784. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34785. }
  34786. }
  34787. }
  34788. if (!flat) {
  34789. for (i = 0; i < data.vertex.length; i++) {
  34790. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34791. uvs.push(0, 0);
  34792. }
  34793. for (f = 0; f < nbfaces; f++) {
  34794. for (i = 0; i < data.face[f].length - 2; i++) {
  34795. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34796. }
  34797. }
  34798. }
  34799. else {
  34800. for (f = 0; f < nbfaces; f++) {
  34801. var fl = data.face[f].length; // number of vertices of the current face
  34802. ang = 2 * Math.PI / fl;
  34803. x = 0.5 * Math.tan(ang / 2);
  34804. y = 0.5;
  34805. // positions, uvs, colors
  34806. for (i = 0; i < fl; i++) {
  34807. // positions
  34808. 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);
  34809. indexes.push(index);
  34810. index++;
  34811. // uvs
  34812. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34813. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34814. uvs.push(u, v);
  34815. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34816. y = x * Math.sin(ang) + y * Math.cos(ang);
  34817. x = tmp;
  34818. // colors
  34819. if (faceColors) {
  34820. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34821. }
  34822. }
  34823. // indices from indexes
  34824. for (i = 0; i < fl - 2; i++) {
  34825. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34826. }
  34827. faceIdx += fl;
  34828. }
  34829. }
  34830. VertexData.ComputeNormals(positions, indices, normals);
  34831. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34832. var vertexData = new VertexData();
  34833. vertexData.positions = positions;
  34834. vertexData.indices = indices;
  34835. vertexData.normals = normals;
  34836. vertexData.uvs = uvs;
  34837. if (faceColors && flat) {
  34838. vertexData.colors = colors;
  34839. }
  34840. return vertexData;
  34841. };
  34842. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34843. /**
  34844. * Creates the VertexData of the Torus Knot.
  34845. */
  34846. VertexData.CreateTorusKnot = function (options) {
  34847. var indices = new Array();
  34848. var positions = new Array();
  34849. var normals = new Array();
  34850. var uvs = new Array();
  34851. var radius = options.radius || 2;
  34852. var tube = options.tube || 0.5;
  34853. var radialSegments = options.radialSegments || 32;
  34854. var tubularSegments = options.tubularSegments || 32;
  34855. var p = options.p || 2;
  34856. var q = options.q || 3;
  34857. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34858. // Helper
  34859. var getPos = function (angle) {
  34860. var cu = Math.cos(angle);
  34861. var su = Math.sin(angle);
  34862. var quOverP = q / p * angle;
  34863. var cs = Math.cos(quOverP);
  34864. var tx = radius * (2 + cs) * 0.5 * cu;
  34865. var ty = radius * (2 + cs) * su * 0.5;
  34866. var tz = radius * Math.sin(quOverP) * 0.5;
  34867. return new BABYLON.Vector3(tx, ty, tz);
  34868. };
  34869. // Vertices
  34870. var i;
  34871. var j;
  34872. for (i = 0; i <= radialSegments; i++) {
  34873. var modI = i % radialSegments;
  34874. var u = modI / radialSegments * 2 * p * Math.PI;
  34875. var p1 = getPos(u);
  34876. var p2 = getPos(u + 0.01);
  34877. var tang = p2.subtract(p1);
  34878. var n = p2.add(p1);
  34879. var bitan = BABYLON.Vector3.Cross(tang, n);
  34880. n = BABYLON.Vector3.Cross(bitan, tang);
  34881. bitan.normalize();
  34882. n.normalize();
  34883. for (j = 0; j < tubularSegments; j++) {
  34884. var modJ = j % tubularSegments;
  34885. var v = modJ / tubularSegments * 2 * Math.PI;
  34886. var cx = -tube * Math.cos(v);
  34887. var cy = tube * Math.sin(v);
  34888. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34889. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34890. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34891. uvs.push(i / radialSegments);
  34892. uvs.push(j / tubularSegments);
  34893. }
  34894. }
  34895. for (i = 0; i < radialSegments; i++) {
  34896. for (j = 0; j < tubularSegments; j++) {
  34897. var jNext = (j + 1) % tubularSegments;
  34898. var a = i * tubularSegments + j;
  34899. var b = (i + 1) * tubularSegments + j;
  34900. var c = (i + 1) * tubularSegments + jNext;
  34901. var d = i * tubularSegments + jNext;
  34902. indices.push(d);
  34903. indices.push(b);
  34904. indices.push(a);
  34905. indices.push(d);
  34906. indices.push(c);
  34907. indices.push(b);
  34908. }
  34909. }
  34910. // Normals
  34911. VertexData.ComputeNormals(positions, indices, normals);
  34912. // Sides
  34913. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34914. // Result
  34915. var vertexData = new VertexData();
  34916. vertexData.indices = indices;
  34917. vertexData.positions = positions;
  34918. vertexData.normals = normals;
  34919. vertexData.uvs = uvs;
  34920. return vertexData;
  34921. };
  34922. // Tools
  34923. /**
  34924. * @param {any} - positions (number[] or Float32Array)
  34925. * @param {any} - indices (number[] or Uint16Array)
  34926. * @param {any} - normals (number[] or Float32Array)
  34927. * options (optional) :
  34928. * facetPositions : optional array of facet positions (vector3)
  34929. * facetNormals : optional array of facet normals (vector3)
  34930. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34931. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34932. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34933. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34934. * bInfo : optional bounding info, required for facetPartitioning computation
  34935. * useRightHandedSystem: optional boolean to for right handed system computation
  34936. * depthSort : optional boolean to enable the facet depth sort computation
  34937. * distanceTo : optional Vector3 to compute the facet depth from this location
  34938. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34939. */
  34940. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34941. // temporary scalar variables
  34942. var index = 0; // facet index
  34943. var p1p2x = 0.0; // p1p2 vector x coordinate
  34944. var p1p2y = 0.0; // p1p2 vector y coordinate
  34945. var p1p2z = 0.0; // p1p2 vector z coordinate
  34946. var p3p2x = 0.0; // p3p2 vector x coordinate
  34947. var p3p2y = 0.0; // p3p2 vector y coordinate
  34948. var p3p2z = 0.0; // p3p2 vector z coordinate
  34949. var faceNormalx = 0.0; // facet normal x coordinate
  34950. var faceNormaly = 0.0; // facet normal y coordinate
  34951. var faceNormalz = 0.0; // facet normal z coordinate
  34952. var length = 0.0; // facet normal length before normalization
  34953. var v1x = 0; // vector1 x index in the positions array
  34954. var v1y = 0; // vector1 y index in the positions array
  34955. var v1z = 0; // vector1 z index in the positions array
  34956. var v2x = 0; // vector2 x index in the positions array
  34957. var v2y = 0; // vector2 y index in the positions array
  34958. var v2z = 0; // vector2 z index in the positions array
  34959. var v3x = 0; // vector3 x index in the positions array
  34960. var v3y = 0; // vector3 y index in the positions array
  34961. var v3z = 0; // vector3 z index in the positions array
  34962. var computeFacetNormals = false;
  34963. var computeFacetPositions = false;
  34964. var computeFacetPartitioning = false;
  34965. var computeDepthSort = false;
  34966. var faceNormalSign = 1;
  34967. var ratio = 0;
  34968. var distanceTo = null;
  34969. if (options) {
  34970. computeFacetNormals = (options.facetNormals) ? true : false;
  34971. computeFacetPositions = (options.facetPositions) ? true : false;
  34972. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34973. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34974. ratio = options.ratio || 0;
  34975. computeDepthSort = (options.depthSort) ? true : false;
  34976. distanceTo = (options.distanceTo);
  34977. if (computeDepthSort) {
  34978. if (distanceTo === undefined) {
  34979. distanceTo = BABYLON.Vector3.Zero();
  34980. }
  34981. var depthSortedFacets = options.depthSortedFacets;
  34982. }
  34983. }
  34984. // facetPartitioning reinit if needed
  34985. var xSubRatio = 0;
  34986. var ySubRatio = 0;
  34987. var zSubRatio = 0;
  34988. var subSq = 0;
  34989. if (computeFacetPartitioning && options && options.bbSize) {
  34990. var ox = 0; // X partitioning index for facet position
  34991. var oy = 0; // Y partinioning index for facet position
  34992. var oz = 0; // Z partinioning index for facet position
  34993. var b1x = 0; // X partitioning index for facet v1 vertex
  34994. var b1y = 0; // Y partitioning index for facet v1 vertex
  34995. var b1z = 0; // z partitioning index for facet v1 vertex
  34996. var b2x = 0; // X partitioning index for facet v2 vertex
  34997. var b2y = 0; // Y partitioning index for facet v2 vertex
  34998. var b2z = 0; // Z partitioning index for facet v2 vertex
  34999. var b3x = 0; // X partitioning index for facet v3 vertex
  35000. var b3y = 0; // Y partitioning index for facet v3 vertex
  35001. var b3z = 0; // Z partitioning index for facet v3 vertex
  35002. var block_idx_o = 0; // facet barycenter block index
  35003. var block_idx_v1 = 0; // v1 vertex block index
  35004. var block_idx_v2 = 0; // v2 vertex block index
  35005. var block_idx_v3 = 0; // v3 vertex block index
  35006. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  35007. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  35008. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  35009. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  35010. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  35011. subSq = options.subDiv.max * options.subDiv.max;
  35012. options.facetPartitioning.length = 0;
  35013. }
  35014. // reset the normals
  35015. for (index = 0; index < positions.length; index++) {
  35016. normals[index] = 0.0;
  35017. }
  35018. // Loop : 1 indice triplet = 1 facet
  35019. var nbFaces = (indices.length / 3) | 0;
  35020. for (index = 0; index < nbFaces; index++) {
  35021. // get the indexes of the coordinates of each vertex of the facet
  35022. v1x = indices[index * 3] * 3;
  35023. v1y = v1x + 1;
  35024. v1z = v1x + 2;
  35025. v2x = indices[index * 3 + 1] * 3;
  35026. v2y = v2x + 1;
  35027. v2z = v2x + 2;
  35028. v3x = indices[index * 3 + 2] * 3;
  35029. v3y = v3x + 1;
  35030. v3z = v3x + 2;
  35031. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  35032. p1p2y = positions[v1y] - positions[v2y];
  35033. p1p2z = positions[v1z] - positions[v2z];
  35034. p3p2x = positions[v3x] - positions[v2x];
  35035. p3p2y = positions[v3y] - positions[v2y];
  35036. p3p2z = positions[v3z] - positions[v2z];
  35037. // compute the face normal with the cross product
  35038. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  35039. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  35040. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  35041. // normalize this normal and store it in the array facetData
  35042. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35043. length = (length === 0) ? 1.0 : length;
  35044. faceNormalx /= length;
  35045. faceNormaly /= length;
  35046. faceNormalz /= length;
  35047. if (computeFacetNormals && options) {
  35048. options.facetNormals[index].x = faceNormalx;
  35049. options.facetNormals[index].y = faceNormaly;
  35050. options.facetNormals[index].z = faceNormalz;
  35051. }
  35052. if (computeFacetPositions && options) {
  35053. // compute and the facet barycenter coordinates in the array facetPositions
  35054. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35055. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35056. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35057. }
  35058. if (computeFacetPartitioning && options) {
  35059. // store the facet indexes in arrays in the main facetPartitioning array :
  35060. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35061. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35062. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35063. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35064. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35065. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35066. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35067. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35068. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35069. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35070. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35071. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35072. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35073. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35074. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35075. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35076. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35077. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35078. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35079. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35080. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35081. // push each facet index in each block containing the vertex
  35082. options.facetPartitioning[block_idx_v1].push(index);
  35083. if (block_idx_v2 != block_idx_v1) {
  35084. options.facetPartitioning[block_idx_v2].push(index);
  35085. }
  35086. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35087. options.facetPartitioning[block_idx_v3].push(index);
  35088. }
  35089. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35090. options.facetPartitioning[block_idx_o].push(index);
  35091. }
  35092. }
  35093. if (computeDepthSort && options && options.facetPositions) {
  35094. var dsf = depthSortedFacets[index];
  35095. dsf.ind = index * 3;
  35096. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35097. }
  35098. // compute the normals anyway
  35099. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35100. normals[v1y] += faceNormaly;
  35101. normals[v1z] += faceNormalz;
  35102. normals[v2x] += faceNormalx;
  35103. normals[v2y] += faceNormaly;
  35104. normals[v2z] += faceNormalz;
  35105. normals[v3x] += faceNormalx;
  35106. normals[v3y] += faceNormaly;
  35107. normals[v3z] += faceNormalz;
  35108. }
  35109. // last normalization of each normal
  35110. for (index = 0; index < normals.length / 3; index++) {
  35111. faceNormalx = normals[index * 3];
  35112. faceNormaly = normals[index * 3 + 1];
  35113. faceNormalz = normals[index * 3 + 2];
  35114. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35115. length = (length === 0) ? 1.0 : length;
  35116. faceNormalx /= length;
  35117. faceNormaly /= length;
  35118. faceNormalz /= length;
  35119. normals[index * 3] = faceNormalx;
  35120. normals[index * 3 + 1] = faceNormaly;
  35121. normals[index * 3 + 2] = faceNormalz;
  35122. }
  35123. };
  35124. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35125. var li = indices.length;
  35126. var ln = normals.length;
  35127. var i;
  35128. var n;
  35129. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35130. switch (sideOrientation) {
  35131. case BABYLON.Mesh.FRONTSIDE:
  35132. // nothing changed
  35133. break;
  35134. case BABYLON.Mesh.BACKSIDE:
  35135. var tmp;
  35136. // indices
  35137. for (i = 0; i < li; i += 3) {
  35138. tmp = indices[i];
  35139. indices[i] = indices[i + 2];
  35140. indices[i + 2] = tmp;
  35141. }
  35142. // normals
  35143. for (n = 0; n < ln; n++) {
  35144. normals[n] = -normals[n];
  35145. }
  35146. break;
  35147. case BABYLON.Mesh.DOUBLESIDE:
  35148. // positions
  35149. var lp = positions.length;
  35150. var l = lp / 3;
  35151. for (var p = 0; p < lp; p++) {
  35152. positions[lp + p] = positions[p];
  35153. }
  35154. // indices
  35155. for (i = 0; i < li; i += 3) {
  35156. indices[i + li] = indices[i + 2] + l;
  35157. indices[i + 1 + li] = indices[i + 1] + l;
  35158. indices[i + 2 + li] = indices[i] + l;
  35159. }
  35160. // normals
  35161. for (n = 0; n < ln; n++) {
  35162. normals[ln + n] = -normals[n];
  35163. }
  35164. // uvs
  35165. var lu = uvs.length;
  35166. var u = 0;
  35167. for (u = 0; u < lu; u++) {
  35168. uvs[u + lu] = uvs[u];
  35169. }
  35170. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35171. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35172. u = 0;
  35173. for (i = 0; i < lu / 2; i++) {
  35174. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35175. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35176. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35177. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35178. u += 2;
  35179. }
  35180. break;
  35181. }
  35182. };
  35183. /**
  35184. * Creates a new VertexData from the imported parameters.
  35185. */
  35186. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35187. var vertexData = new VertexData();
  35188. // positions
  35189. var positions = parsedVertexData.positions;
  35190. if (positions) {
  35191. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35192. }
  35193. // normals
  35194. var normals = parsedVertexData.normals;
  35195. if (normals) {
  35196. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35197. }
  35198. // tangents
  35199. var tangents = parsedVertexData.tangents;
  35200. if (tangents) {
  35201. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35202. }
  35203. // uvs
  35204. var uvs = parsedVertexData.uvs;
  35205. if (uvs) {
  35206. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35207. }
  35208. // uv2s
  35209. var uv2s = parsedVertexData.uv2s;
  35210. if (uv2s) {
  35211. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35212. }
  35213. // uv3s
  35214. var uv3s = parsedVertexData.uv3s;
  35215. if (uv3s) {
  35216. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35217. }
  35218. // uv4s
  35219. var uv4s = parsedVertexData.uv4s;
  35220. if (uv4s) {
  35221. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35222. }
  35223. // uv5s
  35224. var uv5s = parsedVertexData.uv5s;
  35225. if (uv5s) {
  35226. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35227. }
  35228. // uv6s
  35229. var uv6s = parsedVertexData.uv6s;
  35230. if (uv6s) {
  35231. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35232. }
  35233. // colors
  35234. var colors = parsedVertexData.colors;
  35235. if (colors) {
  35236. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35237. }
  35238. // matricesIndices
  35239. var matricesIndices = parsedVertexData.matricesIndices;
  35240. if (matricesIndices) {
  35241. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35242. }
  35243. // matricesWeights
  35244. var matricesWeights = parsedVertexData.matricesWeights;
  35245. if (matricesWeights) {
  35246. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35247. }
  35248. // indices
  35249. var indices = parsedVertexData.indices;
  35250. if (indices) {
  35251. vertexData.indices = indices;
  35252. }
  35253. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35254. };
  35255. return VertexData;
  35256. }());
  35257. BABYLON.VertexData = VertexData;
  35258. })(BABYLON || (BABYLON = {}));
  35259. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35260. "use strict";
  35261. var BABYLON;
  35262. (function (BABYLON) {
  35263. /**
  35264. * Class used to store geometry data (vertex buffers + index buffer)
  35265. */
  35266. var Geometry = /** @class */ (function () {
  35267. /**
  35268. * Creates a new geometry
  35269. * @param id defines the unique ID
  35270. * @param scene defines the hosting scene
  35271. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35272. * @param updatable defines if geometry must be updatable (false by default)
  35273. * @param mesh defines the mesh that will be associated with the geometry
  35274. */
  35275. function Geometry(id, scene, vertexData, updatable, mesh) {
  35276. if (updatable === void 0) { updatable = false; }
  35277. if (mesh === void 0) { mesh = null; }
  35278. /**
  35279. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35280. */
  35281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35282. this._totalVertices = 0;
  35283. this._isDisposed = false;
  35284. this._indexBufferIsUpdatable = false;
  35285. this.id = id;
  35286. this._engine = scene.getEngine();
  35287. this._meshes = [];
  35288. this._scene = scene;
  35289. //Init vertex buffer cache
  35290. this._vertexBuffers = {};
  35291. this._indices = [];
  35292. this._updatable = updatable;
  35293. // vertexData
  35294. if (vertexData) {
  35295. this.setAllVerticesData(vertexData, updatable);
  35296. }
  35297. else {
  35298. this._totalVertices = 0;
  35299. this._indices = [];
  35300. }
  35301. if (this._engine.getCaps().vertexArrayObject) {
  35302. this._vertexArrayObjects = {};
  35303. }
  35304. // applyToMesh
  35305. if (mesh) {
  35306. if (mesh.getClassName() === "LinesMesh") {
  35307. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35308. this.updateExtend();
  35309. }
  35310. this.applyToMesh(mesh);
  35311. mesh.computeWorldMatrix(true);
  35312. }
  35313. }
  35314. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35315. /**
  35316. * 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
  35317. */
  35318. get: function () {
  35319. return this._boundingBias;
  35320. },
  35321. /**
  35322. * 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
  35323. */
  35324. set: function (value) {
  35325. if (this._boundingBias && this._boundingBias.equals(value)) {
  35326. return;
  35327. }
  35328. this._boundingBias = value.clone();
  35329. this.updateBoundingInfo(true, null);
  35330. },
  35331. enumerable: true,
  35332. configurable: true
  35333. });
  35334. /**
  35335. * Static function used to attach a new empty geometry to a mesh
  35336. * @param mesh defines the mesh to attach the geometry to
  35337. * @returns the new {BABYLON.Geometry}
  35338. */
  35339. Geometry.CreateGeometryForMesh = function (mesh) {
  35340. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35341. geometry.applyToMesh(mesh);
  35342. return geometry;
  35343. };
  35344. Object.defineProperty(Geometry.prototype, "extend", {
  35345. /**
  35346. * Gets the current extend of the geometry
  35347. */
  35348. get: function () {
  35349. return this._extend;
  35350. },
  35351. enumerable: true,
  35352. configurable: true
  35353. });
  35354. /**
  35355. * Gets the hosting scene
  35356. * @returns the hosting {BABYLON.Scene}
  35357. */
  35358. Geometry.prototype.getScene = function () {
  35359. return this._scene;
  35360. };
  35361. /**
  35362. * Gets the hosting engine
  35363. * @returns the hosting {BABYLON.Engine}
  35364. */
  35365. Geometry.prototype.getEngine = function () {
  35366. return this._engine;
  35367. };
  35368. /**
  35369. * Defines if the geometry is ready to use
  35370. * @returns true if the geometry is ready to be used
  35371. */
  35372. Geometry.prototype.isReady = function () {
  35373. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35374. };
  35375. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35376. /**
  35377. * Gets a value indicating that the geometry should not be serialized
  35378. */
  35379. get: function () {
  35380. for (var index = 0; index < this._meshes.length; index++) {
  35381. if (!this._meshes[index].doNotSerialize) {
  35382. return false;
  35383. }
  35384. }
  35385. return true;
  35386. },
  35387. enumerable: true,
  35388. configurable: true
  35389. });
  35390. /** @ignore */
  35391. Geometry.prototype._rebuild = function () {
  35392. if (this._vertexArrayObjects) {
  35393. this._vertexArrayObjects = {};
  35394. }
  35395. // Index buffer
  35396. if (this._meshes.length !== 0 && this._indices) {
  35397. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35398. }
  35399. // Vertex buffers
  35400. for (var key in this._vertexBuffers) {
  35401. var vertexBuffer = this._vertexBuffers[key];
  35402. vertexBuffer._rebuild();
  35403. }
  35404. };
  35405. /**
  35406. * Affects all gemetry data in one call
  35407. * @param vertexData defines the geometry data
  35408. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35409. */
  35410. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35411. vertexData.applyToGeometry(this, updatable);
  35412. this.notifyUpdate();
  35413. };
  35414. /**
  35415. * Set specific vertex data
  35416. * @param kind defines the data kind (Position, normal, etc...)
  35417. * @param data defines the vertex data to use
  35418. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35419. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35420. */
  35421. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35422. if (updatable === void 0) { updatable = false; }
  35423. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35424. this.setVerticesBuffer(buffer);
  35425. };
  35426. /**
  35427. * Removes a specific vertex data
  35428. * @param kind defines the data kind (Position, normal, etc...)
  35429. */
  35430. Geometry.prototype.removeVerticesData = function (kind) {
  35431. if (this._vertexBuffers[kind]) {
  35432. this._vertexBuffers[kind].dispose();
  35433. delete this._vertexBuffers[kind];
  35434. }
  35435. };
  35436. /**
  35437. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35438. * @param buffer defines the vertex buffer to use
  35439. */
  35440. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35441. var kind = buffer.getKind();
  35442. if (this._vertexBuffers[kind]) {
  35443. this._vertexBuffers[kind].dispose();
  35444. }
  35445. this._vertexBuffers[kind] = buffer;
  35446. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35447. var data = buffer.getData();
  35448. var stride = buffer.getStrideSize();
  35449. this._totalVertices = data.length / stride;
  35450. this.updateExtend(data, stride);
  35451. this._resetPointsArrayCache();
  35452. var meshes = this._meshes;
  35453. var numOfMeshes = meshes.length;
  35454. for (var index = 0; index < numOfMeshes; index++) {
  35455. var mesh = meshes[index];
  35456. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35457. mesh._createGlobalSubMesh(false);
  35458. mesh.computeWorldMatrix(true);
  35459. }
  35460. }
  35461. this.notifyUpdate(kind);
  35462. if (this._vertexArrayObjects) {
  35463. this._disposeVertexArrayObjects();
  35464. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35465. }
  35466. };
  35467. /**
  35468. * Update a specific vertex buffer
  35469. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35470. * It will do nothing if the buffer is not updatable
  35471. * @param kind defines the data kind (Position, normal, etc...)
  35472. * @param data defines the data to use
  35473. * @param offset defines the offset in the target buffer where to store the data
  35474. */
  35475. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35476. var vertexBuffer = this.getVertexBuffer(kind);
  35477. if (!vertexBuffer) {
  35478. return;
  35479. }
  35480. vertexBuffer.updateDirectly(data, offset);
  35481. this.notifyUpdate(kind);
  35482. };
  35483. /**
  35484. * Update a specific vertex buffer
  35485. * This function will create a new buffer if the current one is not updatable
  35486. * @param kind defines the data kind (Position, normal, etc...)
  35487. * @param data defines the data to use
  35488. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35489. */
  35490. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35491. if (updateExtends === void 0) { updateExtends = false; }
  35492. var vertexBuffer = this.getVertexBuffer(kind);
  35493. if (!vertexBuffer) {
  35494. return;
  35495. }
  35496. vertexBuffer.update(data);
  35497. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35498. var stride = vertexBuffer.getStrideSize();
  35499. this._totalVertices = data.length / stride;
  35500. this.updateBoundingInfo(updateExtends, data);
  35501. }
  35502. this.notifyUpdate(kind);
  35503. };
  35504. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35505. if (updateExtends) {
  35506. this.updateExtend(data);
  35507. }
  35508. var meshes = this._meshes;
  35509. var numOfMeshes = meshes.length;
  35510. this._resetPointsArrayCache();
  35511. for (var index = 0; index < numOfMeshes; index++) {
  35512. var mesh = meshes[index];
  35513. if (updateExtends) {
  35514. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35515. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35516. var subMesh = mesh.subMeshes[subIndex];
  35517. subMesh.refreshBoundingInfo();
  35518. }
  35519. }
  35520. }
  35521. };
  35522. /** @ignore */
  35523. Geometry.prototype._bind = function (effect, indexToBind) {
  35524. if (!effect) {
  35525. return;
  35526. }
  35527. if (indexToBind === undefined) {
  35528. indexToBind = this._indexBuffer;
  35529. }
  35530. var vbs = this.getVertexBuffers();
  35531. if (!vbs) {
  35532. return;
  35533. }
  35534. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35535. this._engine.bindBuffers(vbs, indexToBind, effect);
  35536. return;
  35537. }
  35538. // Using VAO
  35539. if (!this._vertexArrayObjects[effect.key]) {
  35540. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35541. }
  35542. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35543. };
  35544. /**
  35545. * Gets total number of vertices
  35546. * @returns the total number of vertices
  35547. */
  35548. Geometry.prototype.getTotalVertices = function () {
  35549. if (!this.isReady()) {
  35550. return 0;
  35551. }
  35552. return this._totalVertices;
  35553. };
  35554. /**
  35555. * Gets a specific vertex data attached to this geometry
  35556. * @param kind defines the data kind (Position, normal, etc...)
  35557. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35558. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35559. * @returns a float array containing vertex data
  35560. */
  35561. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35562. var vertexBuffer = this.getVertexBuffer(kind);
  35563. if (!vertexBuffer) {
  35564. return null;
  35565. }
  35566. var orig = vertexBuffer.getData();
  35567. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35568. return orig;
  35569. }
  35570. else {
  35571. var len = orig.length;
  35572. var copy = [];
  35573. for (var i = 0; i < len; i++) {
  35574. copy.push(orig[i]);
  35575. }
  35576. return copy;
  35577. }
  35578. };
  35579. /**
  35580. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35581. * @param kind defines the data kind (Position, normal, etc...)
  35582. * @returns true if the vertex buffer with the specified kind is updatable
  35583. */
  35584. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35585. var vb = this._vertexBuffers[kind];
  35586. if (!vb) {
  35587. return false;
  35588. }
  35589. return vb.isUpdatable();
  35590. };
  35591. /**
  35592. * Gets a specific vertex buffer
  35593. * @param kind defines the data kind (Position, normal, etc...)
  35594. * @returns a {BABYLON.VertexBuffer}
  35595. */
  35596. Geometry.prototype.getVertexBuffer = function (kind) {
  35597. if (!this.isReady()) {
  35598. return null;
  35599. }
  35600. return this._vertexBuffers[kind];
  35601. };
  35602. /**
  35603. * Returns all vertex buffers
  35604. * @return an object holding all vertex buffers indexed by kind
  35605. */
  35606. Geometry.prototype.getVertexBuffers = function () {
  35607. if (!this.isReady()) {
  35608. return null;
  35609. }
  35610. return this._vertexBuffers;
  35611. };
  35612. /**
  35613. * Gets a boolean indicating if specific vertex buffer is present
  35614. * @param kind defines the data kind (Position, normal, etc...)
  35615. * @returns true if data is present
  35616. */
  35617. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35618. if (!this._vertexBuffers) {
  35619. if (this._delayInfo) {
  35620. return this._delayInfo.indexOf(kind) !== -1;
  35621. }
  35622. return false;
  35623. }
  35624. return this._vertexBuffers[kind] !== undefined;
  35625. };
  35626. /**
  35627. * Gets a list of all attached data kinds (Position, normal, etc...)
  35628. * @returns a list of string containing all kinds
  35629. */
  35630. Geometry.prototype.getVerticesDataKinds = function () {
  35631. var result = [];
  35632. var kind;
  35633. if (!this._vertexBuffers && this._delayInfo) {
  35634. for (kind in this._delayInfo) {
  35635. result.push(kind);
  35636. }
  35637. }
  35638. else {
  35639. for (kind in this._vertexBuffers) {
  35640. result.push(kind);
  35641. }
  35642. }
  35643. return result;
  35644. };
  35645. /**
  35646. * Update index buffer
  35647. * @param indices defines the indices to store in the index buffer
  35648. * @param offset defines the offset in the target buffer where to store the data
  35649. */
  35650. Geometry.prototype.updateIndices = function (indices, offset) {
  35651. if (!this._indexBuffer) {
  35652. return;
  35653. }
  35654. if (!this._indexBufferIsUpdatable) {
  35655. this.setIndices(indices, null, true);
  35656. }
  35657. else {
  35658. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35659. }
  35660. };
  35661. /**
  35662. * Creates a new index buffer
  35663. * @param indices defines the indices to store in the index buffer
  35664. * @param totalVertices defines the total number of vertices (could be null)
  35665. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35666. */
  35667. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35668. if (totalVertices === void 0) { totalVertices = null; }
  35669. if (updatable === void 0) { updatable = false; }
  35670. if (this._indexBuffer) {
  35671. this._engine._releaseBuffer(this._indexBuffer);
  35672. }
  35673. this._disposeVertexArrayObjects();
  35674. this._indices = indices;
  35675. this._indexBufferIsUpdatable = updatable;
  35676. if (this._meshes.length !== 0 && this._indices) {
  35677. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35678. }
  35679. if (totalVertices != undefined) {
  35680. this._totalVertices = totalVertices;
  35681. }
  35682. var meshes = this._meshes;
  35683. var numOfMeshes = meshes.length;
  35684. for (var index = 0; index < numOfMeshes; index++) {
  35685. meshes[index]._createGlobalSubMesh(true);
  35686. }
  35687. this.notifyUpdate();
  35688. };
  35689. /**
  35690. * Return the total number of indices
  35691. * @returns the total number of indices
  35692. */
  35693. Geometry.prototype.getTotalIndices = function () {
  35694. if (!this.isReady()) {
  35695. return 0;
  35696. }
  35697. return this._indices.length;
  35698. };
  35699. /**
  35700. * Gets the index buffer array
  35701. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35702. * @returns the index buffer array
  35703. */
  35704. Geometry.prototype.getIndices = function (copyWhenShared) {
  35705. if (!this.isReady()) {
  35706. return null;
  35707. }
  35708. var orig = this._indices;
  35709. if (!copyWhenShared || this._meshes.length === 1) {
  35710. return orig;
  35711. }
  35712. else {
  35713. var len = orig.length;
  35714. var copy = [];
  35715. for (var i = 0; i < len; i++) {
  35716. copy.push(orig[i]);
  35717. }
  35718. return copy;
  35719. }
  35720. };
  35721. /**
  35722. * Gets the index buffer
  35723. * @return the index buffer
  35724. */
  35725. Geometry.prototype.getIndexBuffer = function () {
  35726. if (!this.isReady()) {
  35727. return null;
  35728. }
  35729. return this._indexBuffer;
  35730. };
  35731. /** @ignore */
  35732. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35733. if (effect === void 0) { effect = null; }
  35734. if (!effect || !this._vertexArrayObjects) {
  35735. return;
  35736. }
  35737. if (this._vertexArrayObjects[effect.key]) {
  35738. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35739. delete this._vertexArrayObjects[effect.key];
  35740. }
  35741. };
  35742. /**
  35743. * Release the associated resources for a specific mesh
  35744. * @param mesh defines the source mesh
  35745. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35746. */
  35747. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35748. var meshes = this._meshes;
  35749. var index = meshes.indexOf(mesh);
  35750. if (index === -1) {
  35751. return;
  35752. }
  35753. meshes.splice(index, 1);
  35754. mesh._geometry = null;
  35755. if (meshes.length === 0 && shouldDispose) {
  35756. this.dispose();
  35757. }
  35758. };
  35759. /**
  35760. * Apply current geometry to a given mesh
  35761. * @param mesh defines the mesh to apply geometry to
  35762. */
  35763. Geometry.prototype.applyToMesh = function (mesh) {
  35764. if (mesh._geometry === this) {
  35765. return;
  35766. }
  35767. var previousGeometry = mesh._geometry;
  35768. if (previousGeometry) {
  35769. previousGeometry.releaseForMesh(mesh);
  35770. }
  35771. var meshes = this._meshes;
  35772. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35773. mesh._geometry = this;
  35774. this._scene.pushGeometry(this);
  35775. meshes.push(mesh);
  35776. if (this.isReady()) {
  35777. this._applyToMesh(mesh);
  35778. }
  35779. else {
  35780. mesh._boundingInfo = this._boundingInfo;
  35781. }
  35782. };
  35783. Geometry.prototype.updateExtend = function (data, stride) {
  35784. if (data === void 0) { data = null; }
  35785. if (!data) {
  35786. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35787. }
  35788. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35789. };
  35790. Geometry.prototype._applyToMesh = function (mesh) {
  35791. var numOfMeshes = this._meshes.length;
  35792. // vertexBuffers
  35793. for (var kind in this._vertexBuffers) {
  35794. if (numOfMeshes === 1) {
  35795. this._vertexBuffers[kind].create();
  35796. }
  35797. var buffer = this._vertexBuffers[kind].getBuffer();
  35798. if (buffer)
  35799. buffer.references = numOfMeshes;
  35800. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35801. if (!this._extend) {
  35802. this.updateExtend(this._vertexBuffers[kind].getData());
  35803. }
  35804. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35805. mesh._createGlobalSubMesh(false);
  35806. //bounding info was just created again, world matrix should be applied again.
  35807. mesh._updateBoundingInfo();
  35808. }
  35809. }
  35810. // indexBuffer
  35811. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35812. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35813. }
  35814. if (this._indexBuffer) {
  35815. this._indexBuffer.references = numOfMeshes;
  35816. }
  35817. };
  35818. Geometry.prototype.notifyUpdate = function (kind) {
  35819. if (this.onGeometryUpdated) {
  35820. this.onGeometryUpdated(this, kind);
  35821. }
  35822. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35823. var mesh = _a[_i];
  35824. mesh._markSubMeshesAsAttributesDirty();
  35825. }
  35826. };
  35827. /**
  35828. * Load the geometry if it was flagged as delay loaded
  35829. * @param scene defines the hosting scene
  35830. * @param onLoaded defines a callback called when the geometry is loaded
  35831. */
  35832. Geometry.prototype.load = function (scene, onLoaded) {
  35833. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35834. return;
  35835. }
  35836. if (this.isReady()) {
  35837. if (onLoaded) {
  35838. onLoaded();
  35839. }
  35840. return;
  35841. }
  35842. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35843. this._queueLoad(scene, onLoaded);
  35844. };
  35845. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35846. var _this = this;
  35847. if (!this.delayLoadingFile) {
  35848. return;
  35849. }
  35850. scene._addPendingData(this);
  35851. scene._loadFile(this.delayLoadingFile, function (data) {
  35852. if (!_this._delayLoadingFunction) {
  35853. return;
  35854. }
  35855. _this._delayLoadingFunction(JSON.parse(data), _this);
  35856. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35857. _this._delayInfo = [];
  35858. scene._removePendingData(_this);
  35859. var meshes = _this._meshes;
  35860. var numOfMeshes = meshes.length;
  35861. for (var index = 0; index < numOfMeshes; index++) {
  35862. _this._applyToMesh(meshes[index]);
  35863. }
  35864. if (onLoaded) {
  35865. onLoaded();
  35866. }
  35867. }, undefined, true);
  35868. };
  35869. /**
  35870. * Invert the geometry to move from a right handed system to a left handed one.
  35871. */
  35872. Geometry.prototype.toLeftHanded = function () {
  35873. // Flip faces
  35874. var tIndices = this.getIndices(false);
  35875. if (tIndices != null && tIndices.length > 0) {
  35876. for (var i = 0; i < tIndices.length; i += 3) {
  35877. var tTemp = tIndices[i + 0];
  35878. tIndices[i + 0] = tIndices[i + 2];
  35879. tIndices[i + 2] = tTemp;
  35880. }
  35881. this.setIndices(tIndices);
  35882. }
  35883. // Negate position.z
  35884. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35885. if (tPositions != null && tPositions.length > 0) {
  35886. for (var i = 0; i < tPositions.length; i += 3) {
  35887. tPositions[i + 2] = -tPositions[i + 2];
  35888. }
  35889. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35890. }
  35891. // Negate normal.z
  35892. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35893. if (tNormals != null && tNormals.length > 0) {
  35894. for (var i = 0; i < tNormals.length; i += 3) {
  35895. tNormals[i + 2] = -tNormals[i + 2];
  35896. }
  35897. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35898. }
  35899. };
  35900. // Cache
  35901. /** @ignore */
  35902. Geometry.prototype._resetPointsArrayCache = function () {
  35903. this._positions = null;
  35904. };
  35905. /** @ignore */
  35906. Geometry.prototype._generatePointsArray = function () {
  35907. if (this._positions)
  35908. return true;
  35909. this._positions = [];
  35910. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35911. if (!data) {
  35912. return false;
  35913. }
  35914. for (var index = 0; index < data.length; index += 3) {
  35915. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35916. }
  35917. return true;
  35918. };
  35919. /**
  35920. * Gets a value indicating if the geometry is disposed
  35921. * @returns true if the geometry was disposed
  35922. */
  35923. Geometry.prototype.isDisposed = function () {
  35924. return this._isDisposed;
  35925. };
  35926. Geometry.prototype._disposeVertexArrayObjects = function () {
  35927. if (this._vertexArrayObjects) {
  35928. for (var kind in this._vertexArrayObjects) {
  35929. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35930. }
  35931. this._vertexArrayObjects = {};
  35932. }
  35933. };
  35934. /**
  35935. * Free all associated resources
  35936. */
  35937. Geometry.prototype.dispose = function () {
  35938. var meshes = this._meshes;
  35939. var numOfMeshes = meshes.length;
  35940. var index;
  35941. for (index = 0; index < numOfMeshes; index++) {
  35942. this.releaseForMesh(meshes[index]);
  35943. }
  35944. this._meshes = [];
  35945. this._disposeVertexArrayObjects();
  35946. for (var kind in this._vertexBuffers) {
  35947. this._vertexBuffers[kind].dispose();
  35948. }
  35949. this._vertexBuffers = {};
  35950. this._totalVertices = 0;
  35951. if (this._indexBuffer) {
  35952. this._engine._releaseBuffer(this._indexBuffer);
  35953. }
  35954. this._indexBuffer = null;
  35955. this._indices = [];
  35956. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35957. this.delayLoadingFile = null;
  35958. this._delayLoadingFunction = null;
  35959. this._delayInfo = [];
  35960. this._boundingInfo = null;
  35961. this._scene.removeGeometry(this);
  35962. this._isDisposed = true;
  35963. };
  35964. /**
  35965. * Clone the current geometry into a new geometry
  35966. * @param id defines the unique ID of the new geometry
  35967. * @returns a new geometry object
  35968. */
  35969. Geometry.prototype.copy = function (id) {
  35970. var vertexData = new BABYLON.VertexData();
  35971. vertexData.indices = [];
  35972. var indices = this.getIndices();
  35973. if (indices) {
  35974. for (var index = 0; index < indices.length; index++) {
  35975. vertexData.indices.push(indices[index]);
  35976. }
  35977. }
  35978. var updatable = false;
  35979. var stopChecking = false;
  35980. var kind;
  35981. for (kind in this._vertexBuffers) {
  35982. // using slice() to make a copy of the array and not just reference it
  35983. var data = this.getVerticesData(kind);
  35984. if (data instanceof Float32Array) {
  35985. vertexData.set(new Float32Array(data), kind);
  35986. }
  35987. else {
  35988. vertexData.set(data.slice(0), kind);
  35989. }
  35990. if (!stopChecking) {
  35991. var vb = this.getVertexBuffer(kind);
  35992. if (vb) {
  35993. updatable = vb.isUpdatable();
  35994. stopChecking = !updatable;
  35995. }
  35996. }
  35997. }
  35998. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35999. geometry.delayLoadState = this.delayLoadState;
  36000. geometry.delayLoadingFile = this.delayLoadingFile;
  36001. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36002. for (kind in this._delayInfo) {
  36003. geometry._delayInfo = geometry._delayInfo || [];
  36004. geometry._delayInfo.push(kind);
  36005. }
  36006. // Bounding info
  36007. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36008. return geometry;
  36009. };
  36010. /**
  36011. * Serialize the current geometry info (and not the vertices data) into a JSON object
  36012. * @return a JSON representation of the current geometry data (without the vertices data)
  36013. */
  36014. Geometry.prototype.serialize = function () {
  36015. var serializationObject = {};
  36016. serializationObject.id = this.id;
  36017. serializationObject.updatable = this._updatable;
  36018. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  36019. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36020. }
  36021. return serializationObject;
  36022. };
  36023. Geometry.prototype.toNumberArray = function (origin) {
  36024. if (Array.isArray(origin)) {
  36025. return origin;
  36026. }
  36027. else {
  36028. return Array.prototype.slice.call(origin);
  36029. }
  36030. };
  36031. /**
  36032. * Serialize all vertices data into a JSON oject
  36033. * @returns a JSON representation of the current geometry data
  36034. */
  36035. Geometry.prototype.serializeVerticeData = function () {
  36036. var serializationObject = this.serialize();
  36037. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36038. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  36039. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  36040. serializationObject.positions._updatable = true;
  36041. }
  36042. }
  36043. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36044. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  36045. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  36046. serializationObject.normals._updatable = true;
  36047. }
  36048. }
  36049. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36050. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  36051. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  36052. serializationObject.tangets._updatable = true;
  36053. }
  36054. }
  36055. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36056. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36057. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36058. serializationObject.uvs._updatable = true;
  36059. }
  36060. }
  36061. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36062. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36063. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36064. serializationObject.uv2s._updatable = true;
  36065. }
  36066. }
  36067. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36068. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36069. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36070. serializationObject.uv3s._updatable = true;
  36071. }
  36072. }
  36073. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36074. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36075. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36076. serializationObject.uv4s._updatable = true;
  36077. }
  36078. }
  36079. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36080. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36081. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36082. serializationObject.uv5s._updatable = true;
  36083. }
  36084. }
  36085. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36086. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36087. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36088. serializationObject.uv6s._updatable = true;
  36089. }
  36090. }
  36091. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36092. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36093. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36094. serializationObject.colors._updatable = true;
  36095. }
  36096. }
  36097. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36098. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36099. serializationObject.matricesIndices._isExpanded = true;
  36100. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36101. serializationObject.matricesIndices._updatable = true;
  36102. }
  36103. }
  36104. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36105. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36106. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36107. serializationObject.matricesWeights._updatable = true;
  36108. }
  36109. }
  36110. serializationObject.indices = this.toNumberArray(this.getIndices());
  36111. return serializationObject;
  36112. };
  36113. // Statics
  36114. /**
  36115. * Extracts a clone of a mesh geometry
  36116. * @param mesh defines the source mesh
  36117. * @param id defines the unique ID of the new geometry object
  36118. * @returns the new geometry object
  36119. */
  36120. Geometry.ExtractFromMesh = function (mesh, id) {
  36121. var geometry = mesh._geometry;
  36122. if (!geometry) {
  36123. return null;
  36124. }
  36125. return geometry.copy(id);
  36126. };
  36127. /**
  36128. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36129. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36130. * Be aware Math.random() could cause collisions, but:
  36131. * "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"
  36132. * @returns a string containing a new GUID
  36133. */
  36134. Geometry.RandomId = function () {
  36135. return BABYLON.Tools.RandomId();
  36136. };
  36137. /** @ignore */
  36138. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36139. var scene = mesh.getScene();
  36140. // Geometry
  36141. var geometryId = parsedGeometry.geometryId;
  36142. if (geometryId) {
  36143. var geometry = scene.getGeometryByID(geometryId);
  36144. if (geometry) {
  36145. geometry.applyToMesh(mesh);
  36146. }
  36147. }
  36148. else if (parsedGeometry instanceof ArrayBuffer) {
  36149. var binaryInfo = mesh._binaryInfo;
  36150. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36151. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36152. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36153. }
  36154. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36155. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36156. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36157. }
  36158. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36159. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36160. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36161. }
  36162. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36163. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36164. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36165. }
  36166. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36167. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36168. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36169. }
  36170. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36171. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36172. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36173. }
  36174. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36175. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36176. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36177. }
  36178. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36179. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36180. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36181. }
  36182. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36183. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36184. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36185. }
  36186. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36187. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36188. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36189. }
  36190. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36191. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36192. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36193. }
  36194. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36195. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36197. }
  36198. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36199. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36200. mesh.setIndices(indicesData, null);
  36201. }
  36202. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36203. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36204. mesh.subMeshes = [];
  36205. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36206. var materialIndex = subMeshesData[(i * 5) + 0];
  36207. var verticesStart = subMeshesData[(i * 5) + 1];
  36208. var verticesCount = subMeshesData[(i * 5) + 2];
  36209. var indexStart = subMeshesData[(i * 5) + 3];
  36210. var indexCount = subMeshesData[(i * 5) + 4];
  36211. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36212. }
  36213. }
  36214. }
  36215. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36216. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36217. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36218. if (parsedGeometry.tangents) {
  36219. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36220. }
  36221. if (parsedGeometry.uvs) {
  36222. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36223. }
  36224. if (parsedGeometry.uvs2) {
  36225. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36226. }
  36227. if (parsedGeometry.uvs3) {
  36228. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36229. }
  36230. if (parsedGeometry.uvs4) {
  36231. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36232. }
  36233. if (parsedGeometry.uvs5) {
  36234. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36235. }
  36236. if (parsedGeometry.uvs6) {
  36237. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36238. }
  36239. if (parsedGeometry.colors) {
  36240. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36241. }
  36242. if (parsedGeometry.matricesIndices) {
  36243. if (!parsedGeometry.matricesIndices._isExpanded) {
  36244. var floatIndices = [];
  36245. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36246. var matricesIndex = parsedGeometry.matricesIndices[i];
  36247. floatIndices.push(matricesIndex & 0x000000FF);
  36248. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36249. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36250. floatIndices.push(matricesIndex >> 24);
  36251. }
  36252. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36253. }
  36254. else {
  36255. delete parsedGeometry.matricesIndices._isExpanded;
  36256. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36257. }
  36258. }
  36259. if (parsedGeometry.matricesIndicesExtra) {
  36260. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36261. var floatIndices = [];
  36262. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36263. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36264. floatIndices.push(matricesIndex & 0x000000FF);
  36265. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36266. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36267. floatIndices.push(matricesIndex >> 24);
  36268. }
  36269. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36270. }
  36271. else {
  36272. delete parsedGeometry.matricesIndices._isExpanded;
  36273. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36274. }
  36275. }
  36276. if (parsedGeometry.matricesWeights) {
  36277. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36278. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36279. }
  36280. if (parsedGeometry.matricesWeightsExtra) {
  36281. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36282. }
  36283. mesh.setIndices(parsedGeometry.indices, null);
  36284. }
  36285. // SubMeshes
  36286. if (parsedGeometry.subMeshes) {
  36287. mesh.subMeshes = [];
  36288. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36289. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36290. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36291. }
  36292. }
  36293. // Flat shading
  36294. if (mesh._shouldGenerateFlatShading) {
  36295. mesh.convertToFlatShadedMesh();
  36296. delete mesh._shouldGenerateFlatShading;
  36297. }
  36298. // Update
  36299. mesh.computeWorldMatrix(true);
  36300. // Octree
  36301. var sceneOctree = scene.selectionOctree;
  36302. if (sceneOctree !== undefined && sceneOctree !== null) {
  36303. sceneOctree.addMesh(mesh);
  36304. }
  36305. };
  36306. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36307. var epsilon = 1e-3;
  36308. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36309. return;
  36310. }
  36311. var noInfluenceBoneIndex = 0.0;
  36312. if (parsedGeometry.skeletonId > -1) {
  36313. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36314. if (!skeleton) {
  36315. return;
  36316. }
  36317. noInfluenceBoneIndex = skeleton.bones.length;
  36318. }
  36319. else {
  36320. return;
  36321. }
  36322. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36323. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36324. var matricesWeights = parsedGeometry.matricesWeights;
  36325. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36326. var influencers = parsedGeometry.numBoneInfluencer;
  36327. var size = matricesWeights.length;
  36328. for (var i = 0; i < size; i += 4) {
  36329. var weight = 0.0;
  36330. var firstZeroWeight = -1;
  36331. for (var j = 0; j < 4; j++) {
  36332. var w = matricesWeights[i + j];
  36333. weight += w;
  36334. if (w < epsilon && firstZeroWeight < 0) {
  36335. firstZeroWeight = j;
  36336. }
  36337. }
  36338. if (matricesWeightsExtra) {
  36339. for (var j = 0; j < 4; j++) {
  36340. var w = matricesWeightsExtra[i + j];
  36341. weight += w;
  36342. if (w < epsilon && firstZeroWeight < 0) {
  36343. firstZeroWeight = j + 4;
  36344. }
  36345. }
  36346. }
  36347. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36348. firstZeroWeight = influencers - 1;
  36349. }
  36350. if (weight > epsilon) {
  36351. var mweight = 1.0 / weight;
  36352. for (var j = 0; j < 4; j++) {
  36353. matricesWeights[i + j] *= mweight;
  36354. }
  36355. if (matricesWeightsExtra) {
  36356. for (var j = 0; j < 4; j++) {
  36357. matricesWeightsExtra[i + j] *= mweight;
  36358. }
  36359. }
  36360. }
  36361. else {
  36362. if (firstZeroWeight >= 4) {
  36363. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36364. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36365. }
  36366. else {
  36367. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36368. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36369. }
  36370. }
  36371. }
  36372. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36373. if (parsedGeometry.matricesWeightsExtra) {
  36374. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36375. }
  36376. };
  36377. /**
  36378. * Create a new geometry from persisted data (Using .babylon file format)
  36379. * @param parsedVertexData defines the persisted data
  36380. * @param scene defines the hosting scene
  36381. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36382. * @returns the new geometry object
  36383. */
  36384. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36385. if (scene.getGeometryByID(parsedVertexData.id)) {
  36386. return null; // null since geometry could be something else than a box...
  36387. }
  36388. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36389. if (BABYLON.Tags) {
  36390. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36391. }
  36392. if (parsedVertexData.delayLoadingFile) {
  36393. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36394. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36395. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36396. geometry._delayInfo = [];
  36397. if (parsedVertexData.hasUVs) {
  36398. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36399. }
  36400. if (parsedVertexData.hasUVs2) {
  36401. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36402. }
  36403. if (parsedVertexData.hasUVs3) {
  36404. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36405. }
  36406. if (parsedVertexData.hasUVs4) {
  36407. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36408. }
  36409. if (parsedVertexData.hasUVs5) {
  36410. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36411. }
  36412. if (parsedVertexData.hasUVs6) {
  36413. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36414. }
  36415. if (parsedVertexData.hasColors) {
  36416. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36417. }
  36418. if (parsedVertexData.hasMatricesIndices) {
  36419. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36420. }
  36421. if (parsedVertexData.hasMatricesWeights) {
  36422. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36423. }
  36424. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36425. }
  36426. else {
  36427. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36428. }
  36429. scene.pushGeometry(geometry, true);
  36430. return geometry;
  36431. };
  36432. return Geometry;
  36433. }());
  36434. BABYLON.Geometry = Geometry;
  36435. // Primitives
  36436. /// Abstract class
  36437. /**
  36438. * Abstract class used to provide common services for all typed geometries
  36439. */
  36440. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36441. __extends(_PrimitiveGeometry, _super);
  36442. /**
  36443. * Creates a new typed geometry
  36444. * @param id defines the unique ID of the geometry
  36445. * @param scene defines the hosting scene
  36446. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36447. * @param mesh defines the hosting mesh (can be null)
  36448. */
  36449. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36450. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36451. if (mesh === void 0) { mesh = null; }
  36452. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36453. _this._canBeRegenerated = _canBeRegenerated;
  36454. _this._beingRegenerated = true;
  36455. _this.regenerate();
  36456. _this._beingRegenerated = false;
  36457. return _this;
  36458. }
  36459. /**
  36460. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36461. * @returns true if the geometry can be regenerated
  36462. */
  36463. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36464. return this._canBeRegenerated;
  36465. };
  36466. /**
  36467. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36468. */
  36469. _PrimitiveGeometry.prototype.regenerate = function () {
  36470. if (!this._canBeRegenerated) {
  36471. return;
  36472. }
  36473. this._beingRegenerated = true;
  36474. this.setAllVerticesData(this._regenerateVertexData(), false);
  36475. this._beingRegenerated = false;
  36476. };
  36477. /**
  36478. * Clone the geometry
  36479. * @param id defines the unique ID of the new geometry
  36480. * @returns the new geometry
  36481. */
  36482. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36483. return _super.prototype.copy.call(this, id);
  36484. };
  36485. // overrides
  36486. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36487. if (!this._beingRegenerated) {
  36488. return;
  36489. }
  36490. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36491. };
  36492. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36493. if (!this._beingRegenerated) {
  36494. return;
  36495. }
  36496. _super.prototype.setVerticesData.call(this, kind, data, false);
  36497. };
  36498. // to override
  36499. /** @ignore */
  36500. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36501. throw new Error("Abstract method");
  36502. };
  36503. _PrimitiveGeometry.prototype.copy = function (id) {
  36504. throw new Error("Must be overriden in sub-classes.");
  36505. };
  36506. _PrimitiveGeometry.prototype.serialize = function () {
  36507. var serializationObject = _super.prototype.serialize.call(this);
  36508. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36509. return serializationObject;
  36510. };
  36511. return _PrimitiveGeometry;
  36512. }(Geometry));
  36513. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36514. /**
  36515. * Creates a ribbon geometry
  36516. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36517. */
  36518. var RibbonGeometry = /** @class */ (function (_super) {
  36519. __extends(RibbonGeometry, _super);
  36520. /**
  36521. * Creates a ribbon geometry
  36522. * @param id defines the unique ID of the geometry
  36523. * @param scene defines the hosting scene
  36524. * @param pathArray defines the array of paths to use
  36525. * @param closeArray defines if the last path and the first path must be joined
  36526. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36527. * @param offset defines the offset between points
  36528. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36529. * @param mesh defines the hosting mesh (can be null)
  36530. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36531. */
  36532. function RibbonGeometry(id, scene,
  36533. /**
  36534. * Defines the array of paths to use
  36535. */
  36536. pathArray,
  36537. /**
  36538. * Defines if the last and first points of each path in your pathArray must be joined
  36539. */
  36540. closeArray,
  36541. /**
  36542. * Defines if the last and first points of each path in your pathArray must be joined
  36543. */
  36544. closePath,
  36545. /**
  36546. * Defines the offset between points
  36547. */
  36548. offset, canBeRegenerated, mesh,
  36549. /**
  36550. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36551. */
  36552. side) {
  36553. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36555. _this.pathArray = pathArray;
  36556. _this.closeArray = closeArray;
  36557. _this.closePath = closePath;
  36558. _this.offset = offset;
  36559. _this.side = side;
  36560. return _this;
  36561. }
  36562. /** @ignore */
  36563. RibbonGeometry.prototype._regenerateVertexData = function () {
  36564. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36565. };
  36566. RibbonGeometry.prototype.copy = function (id) {
  36567. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36568. };
  36569. return RibbonGeometry;
  36570. }(_PrimitiveGeometry));
  36571. BABYLON.RibbonGeometry = RibbonGeometry;
  36572. /**
  36573. * Creates a box geometry
  36574. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36575. */
  36576. var BoxGeometry = /** @class */ (function (_super) {
  36577. __extends(BoxGeometry, _super);
  36578. /**
  36579. * Creates a box geometry
  36580. * @param id defines the unique ID of the geometry
  36581. * @param scene defines the hosting scene
  36582. * @param size defines the zise of the box (width, height and depth are the same)
  36583. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36584. * @param mesh defines the hosting mesh (can be null)
  36585. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36586. */
  36587. function BoxGeometry(id, scene,
  36588. /**
  36589. * Defines the zise of the box (width, height and depth are the same)
  36590. */
  36591. size, canBeRegenerated, mesh,
  36592. /**
  36593. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36594. */
  36595. side) {
  36596. if (mesh === void 0) { mesh = null; }
  36597. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36598. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36599. _this.size = size;
  36600. _this.side = side;
  36601. return _this;
  36602. }
  36603. BoxGeometry.prototype._regenerateVertexData = function () {
  36604. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36605. };
  36606. BoxGeometry.prototype.copy = function (id) {
  36607. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36608. };
  36609. BoxGeometry.prototype.serialize = function () {
  36610. var serializationObject = _super.prototype.serialize.call(this);
  36611. serializationObject.size = this.size;
  36612. return serializationObject;
  36613. };
  36614. BoxGeometry.Parse = function (parsedBox, scene) {
  36615. if (scene.getGeometryByID(parsedBox.id)) {
  36616. return null; // null since geometry could be something else than a box...
  36617. }
  36618. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36619. if (BABYLON.Tags) {
  36620. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36621. }
  36622. scene.pushGeometry(box, true);
  36623. return box;
  36624. };
  36625. return BoxGeometry;
  36626. }(_PrimitiveGeometry));
  36627. BABYLON.BoxGeometry = BoxGeometry;
  36628. /**
  36629. * Creates a sphere geometry
  36630. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36631. */
  36632. var SphereGeometry = /** @class */ (function (_super) {
  36633. __extends(SphereGeometry, _super);
  36634. /**
  36635. * Create a new sphere geometry
  36636. * @param id defines the unique ID of the geometry
  36637. * @param scene defines the hosting scene
  36638. * @param segments defines the number of segments to use to create the sphere
  36639. * @param diameter defines the diameter of the sphere
  36640. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36641. * @param mesh defines the hosting mesh (can be null)
  36642. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36643. */
  36644. function SphereGeometry(id, scene,
  36645. /**
  36646. * Defines the number of segments to use to create the sphere
  36647. */
  36648. segments,
  36649. /**
  36650. * Defines the diameter of the sphere
  36651. */
  36652. diameter, canBeRegenerated, mesh,
  36653. /**
  36654. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36655. */
  36656. side) {
  36657. if (mesh === void 0) { mesh = null; }
  36658. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36659. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36660. _this.segments = segments;
  36661. _this.diameter = diameter;
  36662. _this.side = side;
  36663. return _this;
  36664. }
  36665. SphereGeometry.prototype._regenerateVertexData = function () {
  36666. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36667. };
  36668. SphereGeometry.prototype.copy = function (id) {
  36669. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36670. };
  36671. SphereGeometry.prototype.serialize = function () {
  36672. var serializationObject = _super.prototype.serialize.call(this);
  36673. serializationObject.segments = this.segments;
  36674. serializationObject.diameter = this.diameter;
  36675. return serializationObject;
  36676. };
  36677. SphereGeometry.Parse = function (parsedSphere, scene) {
  36678. if (scene.getGeometryByID(parsedSphere.id)) {
  36679. return null; // null since geometry could be something else than a sphere...
  36680. }
  36681. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36682. if (BABYLON.Tags) {
  36683. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36684. }
  36685. scene.pushGeometry(sphere, true);
  36686. return sphere;
  36687. };
  36688. return SphereGeometry;
  36689. }(_PrimitiveGeometry));
  36690. BABYLON.SphereGeometry = SphereGeometry;
  36691. /**
  36692. * Creates a disc geometry
  36693. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36694. */
  36695. var DiscGeometry = /** @class */ (function (_super) {
  36696. __extends(DiscGeometry, _super);
  36697. /**
  36698. * Creates a new disc geometry
  36699. * @param id defines the unique ID of the geometry
  36700. * @param scene defines the hosting scene
  36701. * @param radius defines the radius of the disc
  36702. * @param tessellation defines the tesselation factor to apply to the disc
  36703. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36704. * @param mesh defines the hosting mesh (can be null)
  36705. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36706. */
  36707. function DiscGeometry(id, scene,
  36708. /**
  36709. * Defines the radius of the disc
  36710. */
  36711. radius,
  36712. /**
  36713. * Defines the tesselation factor to apply to the disc
  36714. */
  36715. tessellation, canBeRegenerated, mesh,
  36716. /**
  36717. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36718. */
  36719. side) {
  36720. if (mesh === void 0) { mesh = null; }
  36721. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36722. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36723. _this.radius = radius;
  36724. _this.tessellation = tessellation;
  36725. _this.side = side;
  36726. return _this;
  36727. }
  36728. DiscGeometry.prototype._regenerateVertexData = function () {
  36729. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36730. };
  36731. DiscGeometry.prototype.copy = function (id) {
  36732. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36733. };
  36734. return DiscGeometry;
  36735. }(_PrimitiveGeometry));
  36736. BABYLON.DiscGeometry = DiscGeometry;
  36737. /**
  36738. * Creates a new cylinder geometry
  36739. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36740. */
  36741. var CylinderGeometry = /** @class */ (function (_super) {
  36742. __extends(CylinderGeometry, _super);
  36743. /**
  36744. * Creates a new cylinder geometry
  36745. * @param id defines the unique ID of the geometry
  36746. * @param scene defines the hosting scene
  36747. * @param height defines the height of the cylinder
  36748. * @param diameterTop defines the diameter of the cylinder's top cap
  36749. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36750. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36751. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36753. * @param mesh defines the hosting mesh (can be null)
  36754. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36755. */
  36756. function CylinderGeometry(id, scene,
  36757. /**
  36758. * Defines the height of the cylinder
  36759. */
  36760. height,
  36761. /**
  36762. * Defines the diameter of the cylinder's top cap
  36763. */
  36764. diameterTop,
  36765. /**
  36766. * Defines the diameter of the cylinder's bottom cap
  36767. */
  36768. diameterBottom,
  36769. /**
  36770. * Defines the tessellation factor to apply to the cylinder
  36771. */
  36772. tessellation,
  36773. /**
  36774. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36775. */
  36776. subdivisions, canBeRegenerated, mesh,
  36777. /**
  36778. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36779. */
  36780. side) {
  36781. if (subdivisions === void 0) { subdivisions = 1; }
  36782. if (mesh === void 0) { mesh = null; }
  36783. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36784. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36785. _this.height = height;
  36786. _this.diameterTop = diameterTop;
  36787. _this.diameterBottom = diameterBottom;
  36788. _this.tessellation = tessellation;
  36789. _this.subdivisions = subdivisions;
  36790. _this.side = side;
  36791. return _this;
  36792. }
  36793. CylinderGeometry.prototype._regenerateVertexData = function () {
  36794. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36795. };
  36796. CylinderGeometry.prototype.copy = function (id) {
  36797. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36798. };
  36799. CylinderGeometry.prototype.serialize = function () {
  36800. var serializationObject = _super.prototype.serialize.call(this);
  36801. serializationObject.height = this.height;
  36802. serializationObject.diameterTop = this.diameterTop;
  36803. serializationObject.diameterBottom = this.diameterBottom;
  36804. serializationObject.tessellation = this.tessellation;
  36805. return serializationObject;
  36806. };
  36807. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36808. if (scene.getGeometryByID(parsedCylinder.id)) {
  36809. return null; // null since geometry could be something else than a cylinder...
  36810. }
  36811. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36812. if (BABYLON.Tags) {
  36813. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36814. }
  36815. scene.pushGeometry(cylinder, true);
  36816. return cylinder;
  36817. };
  36818. return CylinderGeometry;
  36819. }(_PrimitiveGeometry));
  36820. BABYLON.CylinderGeometry = CylinderGeometry;
  36821. /**
  36822. * Creates a new torus geometry
  36823. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36824. */
  36825. var TorusGeometry = /** @class */ (function (_super) {
  36826. __extends(TorusGeometry, _super);
  36827. /**
  36828. * Creates a new torus geometry
  36829. * @param id defines the unique ID of the geometry
  36830. * @param scene defines the hosting scene
  36831. * @param diameter defines the diameter of the torus
  36832. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36833. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36834. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36835. * @param mesh defines the hosting mesh (can be null)
  36836. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36837. */
  36838. function TorusGeometry(id, scene,
  36839. /**
  36840. * Defines the diameter of the torus
  36841. */
  36842. diameter,
  36843. /**
  36844. * Defines the thickness of the torus (ie. internal diameter)
  36845. */
  36846. thickness,
  36847. /**
  36848. * Defines the tesselation factor to apply to the torus
  36849. */
  36850. tessellation, canBeRegenerated, mesh,
  36851. /**
  36852. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36853. */
  36854. side) {
  36855. if (mesh === void 0) { mesh = null; }
  36856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36857. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36858. _this.diameter = diameter;
  36859. _this.thickness = thickness;
  36860. _this.tessellation = tessellation;
  36861. _this.side = side;
  36862. return _this;
  36863. }
  36864. TorusGeometry.prototype._regenerateVertexData = function () {
  36865. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36866. };
  36867. TorusGeometry.prototype.copy = function (id) {
  36868. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36869. };
  36870. TorusGeometry.prototype.serialize = function () {
  36871. var serializationObject = _super.prototype.serialize.call(this);
  36872. serializationObject.diameter = this.diameter;
  36873. serializationObject.thickness = this.thickness;
  36874. serializationObject.tessellation = this.tessellation;
  36875. return serializationObject;
  36876. };
  36877. TorusGeometry.Parse = function (parsedTorus, scene) {
  36878. if (scene.getGeometryByID(parsedTorus.id)) {
  36879. return null; // null since geometry could be something else than a torus...
  36880. }
  36881. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36882. if (BABYLON.Tags) {
  36883. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36884. }
  36885. scene.pushGeometry(torus, true);
  36886. return torus;
  36887. };
  36888. return TorusGeometry;
  36889. }(_PrimitiveGeometry));
  36890. BABYLON.TorusGeometry = TorusGeometry;
  36891. /**
  36892. * Creates a new ground geometry
  36893. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36894. */
  36895. var GroundGeometry = /** @class */ (function (_super) {
  36896. __extends(GroundGeometry, _super);
  36897. /**
  36898. * Creates a new ground geometry
  36899. * @param id defines the unique ID of the geometry
  36900. * @param scene defines the hosting scene
  36901. * @param width defines the width of the ground
  36902. * @param height defines the height of the ground
  36903. * @param subdivisions defines the subdivisions to apply to the ground
  36904. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36905. * @param mesh defines the hosting mesh (can be null)
  36906. */
  36907. function GroundGeometry(id, scene,
  36908. /**
  36909. * Defines the width of the ground
  36910. */
  36911. width,
  36912. /**
  36913. * Defines the height of the ground
  36914. */
  36915. height,
  36916. /**
  36917. * Defines the subdivisions to apply to the ground
  36918. */
  36919. subdivisions, canBeRegenerated, mesh) {
  36920. if (mesh === void 0) { mesh = null; }
  36921. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36922. _this.width = width;
  36923. _this.height = height;
  36924. _this.subdivisions = subdivisions;
  36925. return _this;
  36926. }
  36927. GroundGeometry.prototype._regenerateVertexData = function () {
  36928. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36929. };
  36930. GroundGeometry.prototype.copy = function (id) {
  36931. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36932. };
  36933. GroundGeometry.prototype.serialize = function () {
  36934. var serializationObject = _super.prototype.serialize.call(this);
  36935. serializationObject.width = this.width;
  36936. serializationObject.height = this.height;
  36937. serializationObject.subdivisions = this.subdivisions;
  36938. return serializationObject;
  36939. };
  36940. GroundGeometry.Parse = function (parsedGround, scene) {
  36941. if (scene.getGeometryByID(parsedGround.id)) {
  36942. return null; // null since geometry could be something else than a ground...
  36943. }
  36944. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36945. if (BABYLON.Tags) {
  36946. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36947. }
  36948. scene.pushGeometry(ground, true);
  36949. return ground;
  36950. };
  36951. return GroundGeometry;
  36952. }(_PrimitiveGeometry));
  36953. BABYLON.GroundGeometry = GroundGeometry;
  36954. /**
  36955. * Creates a tiled ground geometry
  36956. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36957. */
  36958. var TiledGroundGeometry = /** @class */ (function (_super) {
  36959. __extends(TiledGroundGeometry, _super);
  36960. /**
  36961. * Creates a tiled ground geometry
  36962. * @param id defines the unique ID of the geometry
  36963. * @param scene defines the hosting scene
  36964. * @param xmin defines the minimum value on X axis
  36965. * @param zmin defines the minimum value on Z axis
  36966. * @param xmax defines the maximum value on X axis
  36967. * @param zmax defines the maximum value on Z axis
  36968. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36969. * @param precision defines the precision to use when computing the tiles
  36970. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36971. * @param mesh defines the hosting mesh (can be null)
  36972. */
  36973. function TiledGroundGeometry(id, scene,
  36974. /**
  36975. * Defines the minimum value on X axis
  36976. */
  36977. xmin,
  36978. /**
  36979. * Defines the minimum value on Z axis
  36980. */
  36981. zmin,
  36982. /**
  36983. * Defines the maximum value on X axis
  36984. */
  36985. xmax,
  36986. /**
  36987. * Defines the maximum value on Z axis
  36988. */
  36989. zmax,
  36990. /**
  36991. * Defines the subdivisions to apply to the ground
  36992. */
  36993. subdivisions,
  36994. /**
  36995. * Defines the precision to use when computing the tiles
  36996. */
  36997. precision, canBeRegenerated, mesh) {
  36998. if (mesh === void 0) { mesh = null; }
  36999. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37000. _this.xmin = xmin;
  37001. _this.zmin = zmin;
  37002. _this.xmax = xmax;
  37003. _this.zmax = zmax;
  37004. _this.subdivisions = subdivisions;
  37005. _this.precision = precision;
  37006. return _this;
  37007. }
  37008. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  37009. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37010. };
  37011. TiledGroundGeometry.prototype.copy = function (id) {
  37012. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37013. };
  37014. return TiledGroundGeometry;
  37015. }(_PrimitiveGeometry));
  37016. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  37017. /**
  37018. * Creates a plane geometry
  37019. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  37020. */
  37021. var PlaneGeometry = /** @class */ (function (_super) {
  37022. __extends(PlaneGeometry, _super);
  37023. /**
  37024. * Creates a plane geometry
  37025. * @param id defines the unique ID of the geometry
  37026. * @param scene defines the hosting scene
  37027. * @param size defines the size of the plane (width === height)
  37028. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37029. * @param mesh defines the hosting mesh (can be null)
  37030. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37031. */
  37032. function PlaneGeometry(id, scene,
  37033. /**
  37034. * Defines the size of the plane (width === height)
  37035. */
  37036. size, canBeRegenerated, mesh,
  37037. /**
  37038. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37039. */
  37040. side) {
  37041. if (mesh === void 0) { mesh = null; }
  37042. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37043. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37044. _this.size = size;
  37045. _this.side = side;
  37046. return _this;
  37047. }
  37048. PlaneGeometry.prototype._regenerateVertexData = function () {
  37049. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37050. };
  37051. PlaneGeometry.prototype.copy = function (id) {
  37052. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37053. };
  37054. PlaneGeometry.prototype.serialize = function () {
  37055. var serializationObject = _super.prototype.serialize.call(this);
  37056. serializationObject.size = this.size;
  37057. return serializationObject;
  37058. };
  37059. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37060. if (scene.getGeometryByID(parsedPlane.id)) {
  37061. return null; // null since geometry could be something else than a ground...
  37062. }
  37063. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37064. if (BABYLON.Tags) {
  37065. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37066. }
  37067. scene.pushGeometry(plane, true);
  37068. return plane;
  37069. };
  37070. return PlaneGeometry;
  37071. }(_PrimitiveGeometry));
  37072. BABYLON.PlaneGeometry = PlaneGeometry;
  37073. /**
  37074. * Creates a torus knot geometry
  37075. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37076. */
  37077. var TorusKnotGeometry = /** @class */ (function (_super) {
  37078. __extends(TorusKnotGeometry, _super);
  37079. /**
  37080. * Creates a torus knot geometry
  37081. * @param id defines the unique ID of the geometry
  37082. * @param scene defines the hosting scene
  37083. * @param radius defines the radius of the torus knot
  37084. * @param tube defines the thickness of the torus knot tube
  37085. * @param radialSegments defines the number of radial segments
  37086. * @param tubularSegments defines the number of tubular segments
  37087. * @param p defines the first number of windings
  37088. * @param q defines the second number of windings
  37089. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37090. * @param mesh defines the hosting mesh (can be null)
  37091. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37092. */
  37093. function TorusKnotGeometry(id, scene,
  37094. /**
  37095. * Defines the radius of the torus knot
  37096. */
  37097. radius,
  37098. /**
  37099. * Defines the thickness of the torus knot tube
  37100. */
  37101. tube,
  37102. /**
  37103. * Defines the number of radial segments
  37104. */
  37105. radialSegments,
  37106. /**
  37107. * Defines the number of tubular segments
  37108. */
  37109. tubularSegments,
  37110. /**
  37111. * Defines the first number of windings
  37112. */
  37113. p,
  37114. /**
  37115. * Defines the second number of windings
  37116. */
  37117. q, canBeRegenerated, mesh,
  37118. /**
  37119. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37120. */
  37121. side) {
  37122. if (mesh === void 0) { mesh = null; }
  37123. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37124. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37125. _this.radius = radius;
  37126. _this.tube = tube;
  37127. _this.radialSegments = radialSegments;
  37128. _this.tubularSegments = tubularSegments;
  37129. _this.p = p;
  37130. _this.q = q;
  37131. _this.side = side;
  37132. return _this;
  37133. }
  37134. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37135. 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 });
  37136. };
  37137. TorusKnotGeometry.prototype.copy = function (id) {
  37138. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37139. };
  37140. TorusKnotGeometry.prototype.serialize = function () {
  37141. var serializationObject = _super.prototype.serialize.call(this);
  37142. serializationObject.radius = this.radius;
  37143. serializationObject.tube = this.tube;
  37144. serializationObject.radialSegments = this.radialSegments;
  37145. serializationObject.tubularSegments = this.tubularSegments;
  37146. serializationObject.p = this.p;
  37147. serializationObject.q = this.q;
  37148. return serializationObject;
  37149. };
  37150. ;
  37151. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37152. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37153. return null; // null since geometry could be something else than a ground...
  37154. }
  37155. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37156. if (BABYLON.Tags) {
  37157. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37158. }
  37159. scene.pushGeometry(torusKnot, true);
  37160. return torusKnot;
  37161. };
  37162. return TorusKnotGeometry;
  37163. }(_PrimitiveGeometry));
  37164. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37165. //}
  37166. })(BABYLON || (BABYLON = {}));
  37167. //# sourceMappingURL=babylon.geometry.js.map
  37168. "use strict";
  37169. var BABYLON;
  37170. (function (BABYLON) {
  37171. /**
  37172. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37173. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37174. */
  37175. var PostProcessManager = /** @class */ (function () {
  37176. /**
  37177. * Creates a new instance PostProcess
  37178. * @param scene The scene that the post process is associated with.
  37179. */
  37180. function PostProcessManager(scene) {
  37181. this._vertexBuffers = {};
  37182. this._scene = scene;
  37183. }
  37184. PostProcessManager.prototype._prepareBuffers = function () {
  37185. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37186. return;
  37187. }
  37188. // VBO
  37189. var vertices = [];
  37190. vertices.push(1, 1);
  37191. vertices.push(-1, 1);
  37192. vertices.push(-1, -1);
  37193. vertices.push(1, -1);
  37194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37195. this._buildIndexBuffer();
  37196. };
  37197. PostProcessManager.prototype._buildIndexBuffer = function () {
  37198. // Indices
  37199. var indices = [];
  37200. indices.push(0);
  37201. indices.push(1);
  37202. indices.push(2);
  37203. indices.push(0);
  37204. indices.push(2);
  37205. indices.push(3);
  37206. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37207. };
  37208. /**
  37209. * Rebuilds the vertex buffers of the manager.
  37210. */
  37211. PostProcessManager.prototype._rebuild = function () {
  37212. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37213. if (!vb) {
  37214. return;
  37215. }
  37216. vb._rebuild();
  37217. this._buildIndexBuffer();
  37218. };
  37219. // Methods
  37220. /**
  37221. * Prepares a frame to be run through a post process.
  37222. * @param sourceTexture The input texture to the post procesess. (default: null)
  37223. * @param postProcesses An array of post processes to be run. (default: null)
  37224. * @returns True if the post processes were able to be run.
  37225. */
  37226. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37227. if (sourceTexture === void 0) { sourceTexture = null; }
  37228. if (postProcesses === void 0) { postProcesses = null; }
  37229. var camera = this._scene.activeCamera;
  37230. if (!camera) {
  37231. return false;
  37232. }
  37233. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37234. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37235. return false;
  37236. }
  37237. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37238. return true;
  37239. };
  37240. /**
  37241. * Manually render a set of post processes to a texture.
  37242. * @param postProcesses An array of post processes to be run.
  37243. * @param targetTexture The target texture to render to.
  37244. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37245. */
  37246. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37247. if (targetTexture === void 0) { targetTexture = null; }
  37248. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37249. var engine = this._scene.getEngine();
  37250. for (var index = 0; index < postProcesses.length; index++) {
  37251. if (index < postProcesses.length - 1) {
  37252. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37253. }
  37254. else {
  37255. if (targetTexture) {
  37256. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37257. }
  37258. else {
  37259. engine.restoreDefaultFramebuffer();
  37260. }
  37261. }
  37262. var pp = postProcesses[index];
  37263. var effect = pp.apply();
  37264. if (effect) {
  37265. pp.onBeforeRenderObservable.notifyObservers(effect);
  37266. // VBOs
  37267. this._prepareBuffers();
  37268. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37269. // Draw order
  37270. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37271. pp.onAfterRenderObservable.notifyObservers(effect);
  37272. }
  37273. }
  37274. // Restore depth buffer
  37275. engine.setDepthBuffer(true);
  37276. engine.setDepthWrite(true);
  37277. };
  37278. /**
  37279. * Finalize the result of the output of the postprocesses.
  37280. * @param doNotPresent If true the result will not be displayed to the screen.
  37281. * @param targetTexture The target texture to render to.
  37282. * @param faceIndex The index of the face to bind the target texture to.
  37283. * @param postProcesses The array of post processes to render.
  37284. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37285. */
  37286. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37287. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37288. var camera = this._scene.activeCamera;
  37289. if (!camera) {
  37290. return;
  37291. }
  37292. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37293. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37294. return;
  37295. }
  37296. var engine = this._scene.getEngine();
  37297. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37298. var pp = postProcesses[index];
  37299. if (index < len - 1) {
  37300. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37301. }
  37302. else {
  37303. if (targetTexture) {
  37304. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37305. }
  37306. else {
  37307. engine.restoreDefaultFramebuffer();
  37308. }
  37309. }
  37310. if (doNotPresent) {
  37311. break;
  37312. }
  37313. var effect = pp.apply();
  37314. if (effect) {
  37315. pp.onBeforeRenderObservable.notifyObservers(effect);
  37316. // VBOs
  37317. this._prepareBuffers();
  37318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37319. // Draw order
  37320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37321. pp.onAfterRenderObservable.notifyObservers(effect);
  37322. }
  37323. }
  37324. // Restore states
  37325. engine.setDepthBuffer(true);
  37326. engine.setDepthWrite(true);
  37327. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37328. };
  37329. /**
  37330. * Disposes of the post process manager.
  37331. */
  37332. PostProcessManager.prototype.dispose = function () {
  37333. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37334. if (buffer) {
  37335. buffer.dispose();
  37336. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37337. }
  37338. if (this._indexBuffer) {
  37339. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37340. this._indexBuffer = null;
  37341. }
  37342. };
  37343. return PostProcessManager;
  37344. }());
  37345. BABYLON.PostProcessManager = PostProcessManager;
  37346. })(BABYLON || (BABYLON = {}));
  37347. //# sourceMappingURL=babylon.postProcessManager.js.map
  37348. "use strict";
  37349. var BABYLON;
  37350. (function (BABYLON) {
  37351. /**
  37352. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37353. */
  37354. var PerformanceMonitor = /** @class */ (function () {
  37355. /**
  37356. * constructor
  37357. * @param frameSampleSize The number of samples required to saturate the sliding window
  37358. */
  37359. function PerformanceMonitor(frameSampleSize) {
  37360. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37361. this._enabled = true;
  37362. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37363. }
  37364. /**
  37365. * Samples current frame
  37366. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37367. */
  37368. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37369. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37370. if (!this._enabled)
  37371. return;
  37372. if (this._lastFrameTimeMs != null) {
  37373. var dt = timeMs - this._lastFrameTimeMs;
  37374. this._rollingFrameTime.add(dt);
  37375. }
  37376. this._lastFrameTimeMs = timeMs;
  37377. };
  37378. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37379. /**
  37380. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37381. * @return Average frame time in milliseconds
  37382. */
  37383. get: function () {
  37384. return this._rollingFrameTime.average;
  37385. },
  37386. enumerable: true,
  37387. configurable: true
  37388. });
  37389. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37390. /**
  37391. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37392. * @return Frame time variance in milliseconds squared
  37393. */
  37394. get: function () {
  37395. return this._rollingFrameTime.variance;
  37396. },
  37397. enumerable: true,
  37398. configurable: true
  37399. });
  37400. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37401. /**
  37402. * Returns the frame time of the most recent frame
  37403. * @return Frame time in milliseconds
  37404. */
  37405. get: function () {
  37406. return this._rollingFrameTime.history(0);
  37407. },
  37408. enumerable: true,
  37409. configurable: true
  37410. });
  37411. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37412. /**
  37413. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37414. * @return Framerate in frames per second
  37415. */
  37416. get: function () {
  37417. return 1000.0 / this._rollingFrameTime.average;
  37418. },
  37419. enumerable: true,
  37420. configurable: true
  37421. });
  37422. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37423. /**
  37424. * Returns the average framerate in frames per second using the most recent frame time
  37425. * @return Framerate in frames per second
  37426. */
  37427. get: function () {
  37428. var history = this._rollingFrameTime.history(0);
  37429. if (history === 0) {
  37430. return 0;
  37431. }
  37432. return 1000.0 / history;
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37438. /**
  37439. * Returns true if enough samples have been taken to completely fill the sliding window
  37440. * @return true if saturated
  37441. */
  37442. get: function () {
  37443. return this._rollingFrameTime.isSaturated();
  37444. },
  37445. enumerable: true,
  37446. configurable: true
  37447. });
  37448. /**
  37449. * Enables contributions to the sliding window sample set
  37450. */
  37451. PerformanceMonitor.prototype.enable = function () {
  37452. this._enabled = true;
  37453. };
  37454. /**
  37455. * Disables contributions to the sliding window sample set
  37456. * Samples will not be interpolated over the disabled period
  37457. */
  37458. PerformanceMonitor.prototype.disable = function () {
  37459. this._enabled = false;
  37460. //clear last sample to avoid interpolating over the disabled period when next enabled
  37461. this._lastFrameTimeMs = null;
  37462. };
  37463. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37464. /**
  37465. * Returns true if sampling is enabled
  37466. * @return true if enabled
  37467. */
  37468. get: function () {
  37469. return this._enabled;
  37470. },
  37471. enumerable: true,
  37472. configurable: true
  37473. });
  37474. /**
  37475. * Resets performance monitor
  37476. */
  37477. PerformanceMonitor.prototype.reset = function () {
  37478. //clear last sample to avoid interpolating over the disabled period when next enabled
  37479. this._lastFrameTimeMs = null;
  37480. //wipe record
  37481. this._rollingFrameTime.reset();
  37482. };
  37483. return PerformanceMonitor;
  37484. }());
  37485. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37486. /**
  37487. * RollingAverage
  37488. *
  37489. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37490. */
  37491. var RollingAverage = /** @class */ (function () {
  37492. /**
  37493. * constructor
  37494. * @param length The number of samples required to saturate the sliding window
  37495. */
  37496. function RollingAverage(length) {
  37497. this._samples = new Array(length);
  37498. this.reset();
  37499. }
  37500. /**
  37501. * Adds a sample to the sample set
  37502. * @param v The sample value
  37503. */
  37504. RollingAverage.prototype.add = function (v) {
  37505. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37506. var delta;
  37507. //we need to check if we've already wrapped round
  37508. if (this.isSaturated()) {
  37509. //remove bottom of stack from mean
  37510. var bottomValue = this._samples[this._pos];
  37511. delta = bottomValue - this.average;
  37512. this.average -= delta / (this._sampleCount - 1);
  37513. this._m2 -= delta * (bottomValue - this.average);
  37514. }
  37515. else {
  37516. this._sampleCount++;
  37517. }
  37518. //add new value to mean
  37519. delta = v - this.average;
  37520. this.average += delta / (this._sampleCount);
  37521. this._m2 += delta * (v - this.average);
  37522. //set the new variance
  37523. this.variance = this._m2 / (this._sampleCount - 1);
  37524. this._samples[this._pos] = v;
  37525. this._pos++;
  37526. this._pos %= this._samples.length; //positive wrap around
  37527. };
  37528. /**
  37529. * Returns previously added values or null if outside of history or outside the sliding window domain
  37530. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37531. * @return Value previously recorded with add() or null if outside of range
  37532. */
  37533. RollingAverage.prototype.history = function (i) {
  37534. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37535. return 0;
  37536. }
  37537. var i0 = this._wrapPosition(this._pos - 1.0);
  37538. return this._samples[this._wrapPosition(i0 - i)];
  37539. };
  37540. /**
  37541. * Returns true if enough samples have been taken to completely fill the sliding window
  37542. * @return true if sample-set saturated
  37543. */
  37544. RollingAverage.prototype.isSaturated = function () {
  37545. return this._sampleCount >= this._samples.length;
  37546. };
  37547. /**
  37548. * Resets the rolling average (equivalent to 0 samples taken so far)
  37549. */
  37550. RollingAverage.prototype.reset = function () {
  37551. this.average = 0;
  37552. this.variance = 0;
  37553. this._sampleCount = 0;
  37554. this._pos = 0;
  37555. this._m2 = 0;
  37556. };
  37557. /**
  37558. * Wraps a value around the sample range boundaries
  37559. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37560. * @return Wrapped position in sample range
  37561. */
  37562. RollingAverage.prototype._wrapPosition = function (i) {
  37563. var max = this._samples.length;
  37564. return ((i % max) + max) % max;
  37565. };
  37566. return RollingAverage;
  37567. }());
  37568. BABYLON.RollingAverage = RollingAverage;
  37569. })(BABYLON || (BABYLON = {}));
  37570. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37571. "use strict";
  37572. var BABYLON;
  37573. (function (BABYLON) {
  37574. /**
  37575. * This groups together the common properties used for image processing either in direct forward pass
  37576. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37577. * or not.
  37578. */
  37579. var ImageProcessingConfiguration = /** @class */ (function () {
  37580. function ImageProcessingConfiguration() {
  37581. /**
  37582. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37583. */
  37584. this.colorCurves = new BABYLON.ColorCurves();
  37585. this._colorCurvesEnabled = false;
  37586. this._colorGradingEnabled = false;
  37587. this._colorGradingWithGreenDepth = true;
  37588. this._colorGradingBGR = true;
  37589. this._exposure = 1.0;
  37590. this._toneMappingEnabled = false;
  37591. this._contrast = 1.0;
  37592. /**
  37593. * Vignette stretch size.
  37594. */
  37595. this.vignetteStretch = 0;
  37596. /**
  37597. * Vignette centre X Offset.
  37598. */
  37599. this.vignetteCentreX = 0;
  37600. /**
  37601. * Vignette centre Y Offset.
  37602. */
  37603. this.vignetteCentreY = 0;
  37604. /**
  37605. * Vignette weight or intensity of the vignette effect.
  37606. */
  37607. this.vignetteWeight = 1.5;
  37608. /**
  37609. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37610. * if vignetteEnabled is set to true.
  37611. */
  37612. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37613. /**
  37614. * Camera field of view used by the Vignette effect.
  37615. */
  37616. this.vignetteCameraFov = 0.5;
  37617. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37618. this._vignetteEnabled = false;
  37619. this._applyByPostProcess = false;
  37620. this._isEnabled = true;
  37621. /**
  37622. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37623. * @type {BABYLON.Observable}
  37624. */
  37625. this.onUpdateParameters = new BABYLON.Observable();
  37626. }
  37627. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37628. /**
  37629. * Gets wether the color curves effect is enabled.
  37630. */
  37631. get: function () {
  37632. return this._colorCurvesEnabled;
  37633. },
  37634. /**
  37635. * Sets wether the color curves effect is enabled.
  37636. */
  37637. set: function (value) {
  37638. if (this._colorCurvesEnabled === value) {
  37639. return;
  37640. }
  37641. this._colorCurvesEnabled = value;
  37642. this._updateParameters();
  37643. },
  37644. enumerable: true,
  37645. configurable: true
  37646. });
  37647. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37648. /**
  37649. * Gets wether the color grading effect is enabled.
  37650. */
  37651. get: function () {
  37652. return this._colorGradingEnabled;
  37653. },
  37654. /**
  37655. * Sets wether the color grading effect is enabled.
  37656. */
  37657. set: function (value) {
  37658. if (this._colorGradingEnabled === value) {
  37659. return;
  37660. }
  37661. this._colorGradingEnabled = value;
  37662. this._updateParameters();
  37663. },
  37664. enumerable: true,
  37665. configurable: true
  37666. });
  37667. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37668. /**
  37669. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37670. */
  37671. get: function () {
  37672. return this._colorGradingWithGreenDepth;
  37673. },
  37674. /**
  37675. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37676. */
  37677. set: function (value) {
  37678. if (this._colorGradingWithGreenDepth === value) {
  37679. return;
  37680. }
  37681. this._colorGradingWithGreenDepth = value;
  37682. this._updateParameters();
  37683. },
  37684. enumerable: true,
  37685. configurable: true
  37686. });
  37687. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37688. /**
  37689. * Gets wether the color grading texture contains BGR values.
  37690. */
  37691. get: function () {
  37692. return this._colorGradingBGR;
  37693. },
  37694. /**
  37695. * Sets wether the color grading texture contains BGR values.
  37696. */
  37697. set: function (value) {
  37698. if (this._colorGradingBGR === value) {
  37699. return;
  37700. }
  37701. this._colorGradingBGR = value;
  37702. this._updateParameters();
  37703. },
  37704. enumerable: true,
  37705. configurable: true
  37706. });
  37707. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37708. /**
  37709. * Gets the Exposure used in the effect.
  37710. */
  37711. get: function () {
  37712. return this._exposure;
  37713. },
  37714. /**
  37715. * Sets the Exposure used in the effect.
  37716. */
  37717. set: function (value) {
  37718. if (this._exposure === value) {
  37719. return;
  37720. }
  37721. this._exposure = value;
  37722. this._updateParameters();
  37723. },
  37724. enumerable: true,
  37725. configurable: true
  37726. });
  37727. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37728. /**
  37729. * Gets wether the tone mapping effect is enabled.
  37730. */
  37731. get: function () {
  37732. return this._toneMappingEnabled;
  37733. },
  37734. /**
  37735. * Sets wether the tone mapping effect is enabled.
  37736. */
  37737. set: function (value) {
  37738. if (this._toneMappingEnabled === value) {
  37739. return;
  37740. }
  37741. this._toneMappingEnabled = value;
  37742. this._updateParameters();
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37748. /**
  37749. * Gets the contrast used in the effect.
  37750. */
  37751. get: function () {
  37752. return this._contrast;
  37753. },
  37754. /**
  37755. * Sets the contrast used in the effect.
  37756. */
  37757. set: function (value) {
  37758. if (this._contrast === value) {
  37759. return;
  37760. }
  37761. this._contrast = value;
  37762. this._updateParameters();
  37763. },
  37764. enumerable: true,
  37765. configurable: true
  37766. });
  37767. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37768. /**
  37769. * Gets the vignette blend mode allowing different kind of effect.
  37770. */
  37771. get: function () {
  37772. return this._vignetteBlendMode;
  37773. },
  37774. /**
  37775. * Sets the vignette blend mode allowing different kind of effect.
  37776. */
  37777. set: function (value) {
  37778. if (this._vignetteBlendMode === value) {
  37779. return;
  37780. }
  37781. this._vignetteBlendMode = value;
  37782. this._updateParameters();
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37788. /**
  37789. * Gets wether the vignette effect is enabled.
  37790. */
  37791. get: function () {
  37792. return this._vignetteEnabled;
  37793. },
  37794. /**
  37795. * Sets wether the vignette effect is enabled.
  37796. */
  37797. set: function (value) {
  37798. if (this._vignetteEnabled === value) {
  37799. return;
  37800. }
  37801. this._vignetteEnabled = value;
  37802. this._updateParameters();
  37803. },
  37804. enumerable: true,
  37805. configurable: true
  37806. });
  37807. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37808. /**
  37809. * Gets wether the image processing is applied through a post process or not.
  37810. */
  37811. get: function () {
  37812. return this._applyByPostProcess;
  37813. },
  37814. /**
  37815. * Sets wether the image processing is applied through a post process or not.
  37816. */
  37817. set: function (value) {
  37818. if (this._applyByPostProcess === value) {
  37819. return;
  37820. }
  37821. this._applyByPostProcess = value;
  37822. this._updateParameters();
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37828. /**
  37829. * Gets wether the image processing is enabled or not.
  37830. */
  37831. get: function () {
  37832. return this._isEnabled;
  37833. },
  37834. /**
  37835. * Sets wether the image processing is enabled or not.
  37836. */
  37837. set: function (value) {
  37838. if (this._isEnabled === value) {
  37839. return;
  37840. }
  37841. this._isEnabled = value;
  37842. this._updateParameters();
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. /**
  37848. * Method called each time the image processing information changes requires to recompile the effect.
  37849. */
  37850. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37851. this.onUpdateParameters.notifyObservers(this);
  37852. };
  37853. ImageProcessingConfiguration.prototype.getClassName = function () {
  37854. return "ImageProcessingConfiguration";
  37855. };
  37856. /**
  37857. * Prepare the list of uniforms associated with the Image Processing effects.
  37858. * @param uniformsList The list of uniforms used in the effect
  37859. * @param defines the list of defines currently in use
  37860. */
  37861. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37862. if (defines.EXPOSURE) {
  37863. uniforms.push("exposureLinear");
  37864. }
  37865. if (defines.CONTRAST) {
  37866. uniforms.push("contrast");
  37867. }
  37868. if (defines.COLORGRADING) {
  37869. uniforms.push("colorTransformSettings");
  37870. }
  37871. if (defines.VIGNETTE) {
  37872. uniforms.push("vInverseScreenSize");
  37873. uniforms.push("vignetteSettings1");
  37874. uniforms.push("vignetteSettings2");
  37875. }
  37876. if (defines.COLORCURVES) {
  37877. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37878. }
  37879. };
  37880. /**
  37881. * Prepare the list of samplers associated with the Image Processing effects.
  37882. * @param uniformsList The list of uniforms used in the effect
  37883. * @param defines the list of defines currently in use
  37884. */
  37885. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37886. if (defines.COLORGRADING) {
  37887. samplersList.push("txColorTransform");
  37888. }
  37889. };
  37890. /**
  37891. * Prepare the list of defines associated to the shader.
  37892. * @param defines the list of defines to complete
  37893. */
  37894. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37895. if (forPostProcess === void 0) { forPostProcess = false; }
  37896. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37897. defines.VIGNETTE = false;
  37898. defines.TONEMAPPING = false;
  37899. defines.CONTRAST = false;
  37900. defines.EXPOSURE = false;
  37901. defines.COLORCURVES = false;
  37902. defines.COLORGRADING = false;
  37903. defines.COLORGRADING3D = false;
  37904. defines.IMAGEPROCESSING = false;
  37905. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37906. return;
  37907. }
  37908. defines.VIGNETTE = this.vignetteEnabled;
  37909. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37910. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37911. defines.TONEMAPPING = this.toneMappingEnabled;
  37912. defines.CONTRAST = (this.contrast !== 1.0);
  37913. defines.EXPOSURE = (this.exposure !== 1.0);
  37914. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37915. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37916. if (defines.COLORGRADING) {
  37917. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37918. }
  37919. else {
  37920. defines.COLORGRADING3D = false;
  37921. }
  37922. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37923. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37924. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37925. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37926. };
  37927. /**
  37928. * Returns true if all the image processing information are ready.
  37929. */
  37930. ImageProcessingConfiguration.prototype.isReady = function () {
  37931. // Color Grading texure can not be none blocking.
  37932. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37933. };
  37934. /**
  37935. * Binds the image processing to the shader.
  37936. * @param effect The effect to bind to
  37937. */
  37938. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37939. if (aspectRatio === void 0) { aspectRatio = 1; }
  37940. // Color Curves
  37941. if (this._colorCurvesEnabled && this.colorCurves) {
  37942. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37943. }
  37944. // Vignette
  37945. if (this._vignetteEnabled) {
  37946. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37947. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37948. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37949. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37950. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37951. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37952. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37953. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37954. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37955. var vignettePower = -2.0 * this.vignetteWeight;
  37956. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37957. }
  37958. // Exposure
  37959. effect.setFloat("exposureLinear", this.exposure);
  37960. // Contrast
  37961. effect.setFloat("contrast", this.contrast);
  37962. // Color transform settings
  37963. if (this.colorGradingTexture) {
  37964. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37965. var textureSize = this.colorGradingTexture.getSize().height;
  37966. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37967. 0.5 / textureSize, // textureOffset
  37968. textureSize, // textureSize
  37969. this.colorGradingTexture.level // weight
  37970. );
  37971. }
  37972. };
  37973. /**
  37974. * Clones the current image processing instance.
  37975. * @return The cloned image processing
  37976. */
  37977. ImageProcessingConfiguration.prototype.clone = function () {
  37978. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37979. };
  37980. /**
  37981. * Serializes the current image processing instance to a json representation.
  37982. * @return a JSON representation
  37983. */
  37984. ImageProcessingConfiguration.prototype.serialize = function () {
  37985. return BABYLON.SerializationHelper.Serialize(this);
  37986. };
  37987. /**
  37988. * Parses the image processing from a json representation.
  37989. * @param source the JSON source to parse
  37990. * @return The parsed image processing
  37991. */
  37992. ImageProcessingConfiguration.Parse = function (source) {
  37993. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37994. };
  37995. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37996. /**
  37997. * Used to apply the vignette as a mix with the pixel color.
  37998. */
  37999. get: function () {
  38000. return this._VIGNETTEMODE_MULTIPLY;
  38001. },
  38002. enumerable: true,
  38003. configurable: true
  38004. });
  38005. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  38006. /**
  38007. * Used to apply the vignette as a replacement of the pixel color.
  38008. */
  38009. get: function () {
  38010. return this._VIGNETTEMODE_OPAQUE;
  38011. },
  38012. enumerable: true,
  38013. configurable: true
  38014. });
  38015. // Static constants associated to the image processing.
  38016. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38017. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38018. __decorate([
  38019. BABYLON.serializeAsColorCurves()
  38020. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38021. __decorate([
  38022. BABYLON.serialize()
  38023. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38024. __decorate([
  38025. BABYLON.serializeAsTexture()
  38026. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38027. __decorate([
  38028. BABYLON.serialize()
  38029. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38030. __decorate([
  38031. BABYLON.serialize()
  38032. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38033. __decorate([
  38034. BABYLON.serialize()
  38035. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38036. __decorate([
  38037. BABYLON.serialize()
  38038. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38039. __decorate([
  38040. BABYLON.serialize()
  38041. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38042. __decorate([
  38043. BABYLON.serialize()
  38044. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38045. __decorate([
  38046. BABYLON.serialize()
  38047. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38048. __decorate([
  38049. BABYLON.serialize()
  38050. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38051. __decorate([
  38052. BABYLON.serialize()
  38053. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38054. __decorate([
  38055. BABYLON.serialize()
  38056. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38057. __decorate([
  38058. BABYLON.serializeAsColor4()
  38059. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38060. __decorate([
  38061. BABYLON.serialize()
  38062. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38063. __decorate([
  38064. BABYLON.serialize()
  38065. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38066. __decorate([
  38067. BABYLON.serialize()
  38068. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38069. __decorate([
  38070. BABYLON.serialize()
  38071. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38072. __decorate([
  38073. BABYLON.serialize()
  38074. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38075. return ImageProcessingConfiguration;
  38076. }());
  38077. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38078. })(BABYLON || (BABYLON = {}));
  38079. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38080. "use strict";
  38081. var BABYLON;
  38082. (function (BABYLON) {
  38083. /**
  38084. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38085. * It can help converting any input color in a desired output one. This can then be used to create effects
  38086. * from sepia, black and white to sixties or futuristic rendering...
  38087. *
  38088. * The only supported format is currently 3dl.
  38089. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38090. */
  38091. var ColorGradingTexture = /** @class */ (function (_super) {
  38092. __extends(ColorGradingTexture, _super);
  38093. /**
  38094. * Instantiates a ColorGradingTexture from the following parameters.
  38095. *
  38096. * @param url The location of the color gradind data (currently only supporting 3dl)
  38097. * @param scene The scene the texture will be used in
  38098. */
  38099. function ColorGradingTexture(url, scene) {
  38100. var _this = _super.call(this, scene) || this;
  38101. if (!url) {
  38102. return _this;
  38103. }
  38104. _this._engine = scene.getEngine();
  38105. _this._textureMatrix = BABYLON.Matrix.Identity();
  38106. _this.name = url;
  38107. _this.url = url;
  38108. _this.hasAlpha = false;
  38109. _this.isCube = false;
  38110. _this.is3D = _this._engine.webGLVersion > 1;
  38111. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38112. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38113. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38114. _this.anisotropicFilteringLevel = 1;
  38115. _this._texture = _this._getFromCache(url, true);
  38116. if (!_this._texture) {
  38117. if (!scene.useDelayedTextureLoading) {
  38118. _this.loadTexture();
  38119. }
  38120. else {
  38121. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38122. }
  38123. }
  38124. return _this;
  38125. }
  38126. /**
  38127. * Returns the texture matrix used in most of the material.
  38128. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38129. */
  38130. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38131. return this._textureMatrix;
  38132. };
  38133. /**
  38134. * Occurs when the file being loaded is a .3dl LUT file.
  38135. */
  38136. ColorGradingTexture.prototype.load3dlTexture = function () {
  38137. var engine = this._engine;
  38138. var texture;
  38139. if (engine.webGLVersion === 1) {
  38140. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38141. }
  38142. else {
  38143. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38144. }
  38145. this._texture = texture;
  38146. var callback = function (text) {
  38147. if (typeof text !== "string") {
  38148. return;
  38149. }
  38150. var data = null;
  38151. var tempData = null;
  38152. var line;
  38153. var lines = text.split('\n');
  38154. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38155. var maxColor = 0;
  38156. for (var i = 0; i < lines.length; i++) {
  38157. line = lines[i];
  38158. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38159. continue;
  38160. if (line.indexOf('#') === 0)
  38161. continue;
  38162. var words = line.split(" ");
  38163. if (size === 0) {
  38164. // Number of space + one
  38165. size = words.length;
  38166. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38167. tempData = new Float32Array(size * size * size * 4);
  38168. continue;
  38169. }
  38170. if (size != 0) {
  38171. var r = Math.max(parseInt(words[0]), 0);
  38172. var g = Math.max(parseInt(words[1]), 0);
  38173. var b = Math.max(parseInt(words[2]), 0);
  38174. maxColor = Math.max(r, maxColor);
  38175. maxColor = Math.max(g, maxColor);
  38176. maxColor = Math.max(b, maxColor);
  38177. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38178. if (tempData) {
  38179. tempData[pixelStorageIndex + 0] = r;
  38180. tempData[pixelStorageIndex + 1] = g;
  38181. tempData[pixelStorageIndex + 2] = b;
  38182. }
  38183. pixelIndexSlice++;
  38184. if (pixelIndexSlice % size == 0) {
  38185. pixelIndexH++;
  38186. pixelIndexSlice = 0;
  38187. if (pixelIndexH % size == 0) {
  38188. pixelIndexW++;
  38189. pixelIndexH = 0;
  38190. }
  38191. }
  38192. }
  38193. }
  38194. if (tempData && data) {
  38195. for (var i = 0; i < tempData.length; i++) {
  38196. if (i > 0 && (i + 1) % 4 === 0) {
  38197. data[i] = 255;
  38198. }
  38199. else {
  38200. var value = tempData[i];
  38201. data[i] = (value / maxColor * 255);
  38202. }
  38203. }
  38204. }
  38205. if (texture.is3D) {
  38206. texture.updateSize(size, size, size);
  38207. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38208. }
  38209. else {
  38210. texture.updateSize(size * size, size);
  38211. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38212. }
  38213. };
  38214. var scene = this.getScene();
  38215. if (scene) {
  38216. scene._loadFile(this.url, callback);
  38217. }
  38218. else {
  38219. this._engine._loadFile(this.url, callback);
  38220. }
  38221. return this._texture;
  38222. };
  38223. /**
  38224. * Starts the loading process of the texture.
  38225. */
  38226. ColorGradingTexture.prototype.loadTexture = function () {
  38227. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38228. this.load3dlTexture();
  38229. }
  38230. };
  38231. /**
  38232. * Clones the color gradind texture.
  38233. */
  38234. ColorGradingTexture.prototype.clone = function () {
  38235. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38236. // Base texture
  38237. newTexture.level = this.level;
  38238. return newTexture;
  38239. };
  38240. /**
  38241. * Called during delayed load for textures.
  38242. */
  38243. ColorGradingTexture.prototype.delayLoad = function () {
  38244. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38245. return;
  38246. }
  38247. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38248. this._texture = this._getFromCache(this.url, true);
  38249. if (!this._texture) {
  38250. this.loadTexture();
  38251. }
  38252. };
  38253. /**
  38254. * Parses a color grading texture serialized by Babylon.
  38255. * @param parsedTexture The texture information being parsedTexture
  38256. * @param scene The scene to load the texture in
  38257. * @param rootUrl The root url of the data assets to load
  38258. * @return A color gradind texture
  38259. */
  38260. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38261. var texture = null;
  38262. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38263. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38264. texture.name = parsedTexture.name;
  38265. texture.level = parsedTexture.level;
  38266. }
  38267. return texture;
  38268. };
  38269. /**
  38270. * Serializes the LUT texture to json format.
  38271. */
  38272. ColorGradingTexture.prototype.serialize = function () {
  38273. if (!this.name) {
  38274. return null;
  38275. }
  38276. var serializationObject = {};
  38277. serializationObject.name = this.name;
  38278. serializationObject.level = this.level;
  38279. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38280. return serializationObject;
  38281. };
  38282. /**
  38283. * Empty line regex stored for GC.
  38284. */
  38285. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38286. return ColorGradingTexture;
  38287. }(BABYLON.BaseTexture));
  38288. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38289. })(BABYLON || (BABYLON = {}));
  38290. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38291. "use strict";
  38292. var BABYLON;
  38293. (function (BABYLON) {
  38294. /**
  38295. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38296. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38297. * 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;
  38298. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38299. */
  38300. var ColorCurves = /** @class */ (function () {
  38301. function ColorCurves() {
  38302. this._dirty = true;
  38303. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38304. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38305. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38306. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38307. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38308. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38309. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38310. this._globalHue = 30;
  38311. this._globalDensity = 0;
  38312. this._globalSaturation = 0;
  38313. this._globalExposure = 0;
  38314. this._highlightsHue = 30;
  38315. this._highlightsDensity = 0;
  38316. this._highlightsSaturation = 0;
  38317. this._highlightsExposure = 0;
  38318. this._midtonesHue = 30;
  38319. this._midtonesDensity = 0;
  38320. this._midtonesSaturation = 0;
  38321. this._midtonesExposure = 0;
  38322. this._shadowsHue = 30;
  38323. this._shadowsDensity = 0;
  38324. this._shadowsSaturation = 0;
  38325. this._shadowsExposure = 0;
  38326. }
  38327. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38328. /**
  38329. * Gets the global Hue value.
  38330. * 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).
  38331. */
  38332. get: function () {
  38333. return this._globalHue;
  38334. },
  38335. /**
  38336. * Sets the global Hue value.
  38337. * 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).
  38338. */
  38339. set: function (value) {
  38340. this._globalHue = value;
  38341. this._dirty = true;
  38342. },
  38343. enumerable: true,
  38344. configurable: true
  38345. });
  38346. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38347. /**
  38348. * Gets the global Density value.
  38349. * 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.
  38350. * Values less than zero provide a filter of opposite hue.
  38351. */
  38352. get: function () {
  38353. return this._globalDensity;
  38354. },
  38355. /**
  38356. * Sets the global Density value.
  38357. * 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.
  38358. * Values less than zero provide a filter of opposite hue.
  38359. */
  38360. set: function (value) {
  38361. this._globalDensity = value;
  38362. this._dirty = true;
  38363. },
  38364. enumerable: true,
  38365. configurable: true
  38366. });
  38367. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38368. /**
  38369. * Gets the global Saturation value.
  38370. * 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.
  38371. */
  38372. get: function () {
  38373. return this._globalSaturation;
  38374. },
  38375. /**
  38376. * Sets the global Saturation value.
  38377. * 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.
  38378. */
  38379. set: function (value) {
  38380. this._globalSaturation = value;
  38381. this._dirty = true;
  38382. },
  38383. enumerable: true,
  38384. configurable: true
  38385. });
  38386. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38387. /**
  38388. * Gets the highlights Hue value.
  38389. * 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).
  38390. */
  38391. get: function () {
  38392. return this._highlightsHue;
  38393. },
  38394. /**
  38395. * Sets the highlights Hue value.
  38396. * 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).
  38397. */
  38398. set: function (value) {
  38399. this._highlightsHue = value;
  38400. this._dirty = true;
  38401. },
  38402. enumerable: true,
  38403. configurable: true
  38404. });
  38405. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38406. /**
  38407. * Gets the highlights Density value.
  38408. * 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.
  38409. * Values less than zero provide a filter of opposite hue.
  38410. */
  38411. get: function () {
  38412. return this._highlightsDensity;
  38413. },
  38414. /**
  38415. * Sets the highlights Density value.
  38416. * 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.
  38417. * Values less than zero provide a filter of opposite hue.
  38418. */
  38419. set: function (value) {
  38420. this._highlightsDensity = value;
  38421. this._dirty = true;
  38422. },
  38423. enumerable: true,
  38424. configurable: true
  38425. });
  38426. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38427. /**
  38428. * Gets the highlights Saturation value.
  38429. * 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.
  38430. */
  38431. get: function () {
  38432. return this._highlightsSaturation;
  38433. },
  38434. /**
  38435. * Sets the highlights Saturation value.
  38436. * 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.
  38437. */
  38438. set: function (value) {
  38439. this._highlightsSaturation = value;
  38440. this._dirty = true;
  38441. },
  38442. enumerable: true,
  38443. configurable: true
  38444. });
  38445. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38446. /**
  38447. * Gets the highlights Exposure value.
  38448. * 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.
  38449. */
  38450. get: function () {
  38451. return this._highlightsExposure;
  38452. },
  38453. /**
  38454. * Sets the highlights Exposure value.
  38455. * 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.
  38456. */
  38457. set: function (value) {
  38458. this._highlightsExposure = value;
  38459. this._dirty = true;
  38460. },
  38461. enumerable: true,
  38462. configurable: true
  38463. });
  38464. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38465. /**
  38466. * Gets the midtones Hue value.
  38467. * 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).
  38468. */
  38469. get: function () {
  38470. return this._midtonesHue;
  38471. },
  38472. /**
  38473. * Sets the midtones Hue value.
  38474. * 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).
  38475. */
  38476. set: function (value) {
  38477. this._midtonesHue = value;
  38478. this._dirty = true;
  38479. },
  38480. enumerable: true,
  38481. configurable: true
  38482. });
  38483. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38484. /**
  38485. * Gets the midtones Density value.
  38486. * 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.
  38487. * Values less than zero provide a filter of opposite hue.
  38488. */
  38489. get: function () {
  38490. return this._midtonesDensity;
  38491. },
  38492. /**
  38493. * Sets the midtones Density value.
  38494. * 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.
  38495. * Values less than zero provide a filter of opposite hue.
  38496. */
  38497. set: function (value) {
  38498. this._midtonesDensity = value;
  38499. this._dirty = true;
  38500. },
  38501. enumerable: true,
  38502. configurable: true
  38503. });
  38504. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38505. /**
  38506. * Gets the midtones Saturation value.
  38507. * 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.
  38508. */
  38509. get: function () {
  38510. return this._midtonesSaturation;
  38511. },
  38512. /**
  38513. * Sets the midtones Saturation value.
  38514. * 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.
  38515. */
  38516. set: function (value) {
  38517. this._midtonesSaturation = value;
  38518. this._dirty = true;
  38519. },
  38520. enumerable: true,
  38521. configurable: true
  38522. });
  38523. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38524. /**
  38525. * Gets the midtones Exposure value.
  38526. * 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.
  38527. */
  38528. get: function () {
  38529. return this._midtonesExposure;
  38530. },
  38531. /**
  38532. * Sets the midtones Exposure value.
  38533. * 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.
  38534. */
  38535. set: function (value) {
  38536. this._midtonesExposure = value;
  38537. this._dirty = true;
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38543. /**
  38544. * Gets the shadows Hue value.
  38545. * 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).
  38546. */
  38547. get: function () {
  38548. return this._shadowsHue;
  38549. },
  38550. /**
  38551. * Sets the shadows Hue value.
  38552. * 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).
  38553. */
  38554. set: function (value) {
  38555. this._shadowsHue = value;
  38556. this._dirty = true;
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38562. /**
  38563. * Gets the shadows Density value.
  38564. * 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.
  38565. * Values less than zero provide a filter of opposite hue.
  38566. */
  38567. get: function () {
  38568. return this._shadowsDensity;
  38569. },
  38570. /**
  38571. * Sets the shadows Density value.
  38572. * 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.
  38573. * Values less than zero provide a filter of opposite hue.
  38574. */
  38575. set: function (value) {
  38576. this._shadowsDensity = value;
  38577. this._dirty = true;
  38578. },
  38579. enumerable: true,
  38580. configurable: true
  38581. });
  38582. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38583. /**
  38584. * Gets the shadows Saturation value.
  38585. * 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.
  38586. */
  38587. get: function () {
  38588. return this._shadowsSaturation;
  38589. },
  38590. /**
  38591. * Sets the shadows Saturation value.
  38592. * 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.
  38593. */
  38594. set: function (value) {
  38595. this._shadowsSaturation = value;
  38596. this._dirty = true;
  38597. },
  38598. enumerable: true,
  38599. configurable: true
  38600. });
  38601. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38602. /**
  38603. * Gets the shadows Exposure value.
  38604. * 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.
  38605. */
  38606. get: function () {
  38607. return this._shadowsExposure;
  38608. },
  38609. /**
  38610. * Sets the shadows Exposure value.
  38611. * 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.
  38612. */
  38613. set: function (value) {
  38614. this._shadowsExposure = value;
  38615. this._dirty = true;
  38616. },
  38617. enumerable: true,
  38618. configurable: true
  38619. });
  38620. ColorCurves.prototype.getClassName = function () {
  38621. return "ColorCurves";
  38622. };
  38623. /**
  38624. * Binds the color curves to the shader.
  38625. * @param colorCurves The color curve to bind
  38626. * @param effect The effect to bind to
  38627. */
  38628. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38629. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38630. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38631. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38632. if (colorCurves._dirty) {
  38633. colorCurves._dirty = false;
  38634. // Fill in global info.
  38635. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38636. // Compute highlights info.
  38637. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38638. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38639. // Compute midtones info.
  38640. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38641. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38642. // Compute shadows info.
  38643. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38644. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38645. // Compute deltas (neutral is midtones).
  38646. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38647. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38648. }
  38649. if (effect) {
  38650. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38651. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38652. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38653. }
  38654. };
  38655. /**
  38656. * Prepare the list of uniforms associated with the ColorCurves effects.
  38657. * @param uniformsList The list of uniforms used in the effect
  38658. */
  38659. ColorCurves.PrepareUniforms = function (uniformsList) {
  38660. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38661. };
  38662. /**
  38663. * Returns color grading data based on a hue, density, saturation and exposure value.
  38664. * @param filterHue The hue of the color filter.
  38665. * @param filterDensity The density of the color filter.
  38666. * @param saturation The saturation.
  38667. * @param exposure The exposure.
  38668. * @param result The result data container.
  38669. */
  38670. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38671. if (hue == null) {
  38672. return;
  38673. }
  38674. hue = ColorCurves.clamp(hue, 0, 360);
  38675. density = ColorCurves.clamp(density, -100, 100);
  38676. saturation = ColorCurves.clamp(saturation, -100, 100);
  38677. exposure = ColorCurves.clamp(exposure, -100, 100);
  38678. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38679. // so that the maximum filter density is only 50% control. This provides fine control
  38680. // for small values and reasonable range.
  38681. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38682. density *= 0.5;
  38683. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38684. if (density < 0) {
  38685. density *= -1;
  38686. hue = (hue + 180) % 360;
  38687. }
  38688. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38689. result.scaleToRef(2, result);
  38690. result.a = 1 + 0.01 * saturation;
  38691. };
  38692. /**
  38693. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38694. * @param value The input slider value in range [-100,100].
  38695. * @returns Adjusted value.
  38696. */
  38697. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38698. value /= 100;
  38699. var x = Math.abs(value);
  38700. x = Math.pow(x, 2);
  38701. if (value < 0) {
  38702. x *= -1;
  38703. }
  38704. x *= 100;
  38705. return x;
  38706. };
  38707. /**
  38708. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38709. * @param hue The hue (H) input.
  38710. * @param saturation The saturation (S) input.
  38711. * @param brightness The brightness (B) input.
  38712. * @result An RGBA color represented as Vector4.
  38713. */
  38714. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38715. var h = ColorCurves.clamp(hue, 0, 360);
  38716. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38717. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38718. if (s === 0) {
  38719. result.r = v;
  38720. result.g = v;
  38721. result.b = v;
  38722. }
  38723. else {
  38724. // sector 0 to 5
  38725. h /= 60;
  38726. var i = Math.floor(h);
  38727. // fractional part of h
  38728. var f = h - i;
  38729. var p = v * (1 - s);
  38730. var q = v * (1 - s * f);
  38731. var t = v * (1 - s * (1 - f));
  38732. switch (i) {
  38733. case 0:
  38734. result.r = v;
  38735. result.g = t;
  38736. result.b = p;
  38737. break;
  38738. case 1:
  38739. result.r = q;
  38740. result.g = v;
  38741. result.b = p;
  38742. break;
  38743. case 2:
  38744. result.r = p;
  38745. result.g = v;
  38746. result.b = t;
  38747. break;
  38748. case 3:
  38749. result.r = p;
  38750. result.g = q;
  38751. result.b = v;
  38752. break;
  38753. case 4:
  38754. result.r = t;
  38755. result.g = p;
  38756. result.b = v;
  38757. break;
  38758. default:// case 5:
  38759. result.r = v;
  38760. result.g = p;
  38761. result.b = q;
  38762. break;
  38763. }
  38764. }
  38765. result.a = 1;
  38766. };
  38767. /**
  38768. * Returns a value clamped between min and max
  38769. * @param value The value to clamp
  38770. * @param min The minimum of value
  38771. * @param max The maximum of value
  38772. * @returns The clamped value.
  38773. */
  38774. ColorCurves.clamp = function (value, min, max) {
  38775. return Math.min(Math.max(value, min), max);
  38776. };
  38777. /**
  38778. * Clones the current color curve instance.
  38779. * @return The cloned curves
  38780. */
  38781. ColorCurves.prototype.clone = function () {
  38782. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38783. };
  38784. /**
  38785. * Serializes the current color curve instance to a json representation.
  38786. * @return a JSON representation
  38787. */
  38788. ColorCurves.prototype.serialize = function () {
  38789. return BABYLON.SerializationHelper.Serialize(this);
  38790. };
  38791. /**
  38792. * Parses the color curve from a json representation.
  38793. * @param source the JSON source to parse
  38794. * @return The parsed curves
  38795. */
  38796. ColorCurves.Parse = function (source) {
  38797. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38798. };
  38799. __decorate([
  38800. BABYLON.serialize()
  38801. ], ColorCurves.prototype, "_globalHue", void 0);
  38802. __decorate([
  38803. BABYLON.serialize()
  38804. ], ColorCurves.prototype, "_globalDensity", void 0);
  38805. __decorate([
  38806. BABYLON.serialize()
  38807. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38808. __decorate([
  38809. BABYLON.serialize()
  38810. ], ColorCurves.prototype, "_globalExposure", void 0);
  38811. __decorate([
  38812. BABYLON.serialize()
  38813. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38814. __decorate([
  38815. BABYLON.serialize()
  38816. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38817. __decorate([
  38818. BABYLON.serialize()
  38819. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38820. __decorate([
  38821. BABYLON.serialize()
  38822. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38823. __decorate([
  38824. BABYLON.serialize()
  38825. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38826. __decorate([
  38827. BABYLON.serialize()
  38828. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38829. __decorate([
  38830. BABYLON.serialize()
  38831. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38832. __decorate([
  38833. BABYLON.serialize()
  38834. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38835. return ColorCurves;
  38836. }());
  38837. BABYLON.ColorCurves = ColorCurves;
  38838. })(BABYLON || (BABYLON = {}));
  38839. //# sourceMappingURL=babylon.colorCurves.js.map
  38840. "use strict";
  38841. //# sourceMappingURL=babylon.behavior.js.map
  38842. "use strict";
  38843. var BABYLON;
  38844. (function (BABYLON) {
  38845. /**
  38846. * "Static Class" containing the most commonly used helper while dealing with material for
  38847. * rendering purpose.
  38848. *
  38849. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38850. *
  38851. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38852. */
  38853. var MaterialHelper = /** @class */ (function () {
  38854. function MaterialHelper() {
  38855. }
  38856. /**
  38857. * Bind the current view position to an effect.
  38858. * @param effect The effect to be bound
  38859. * @param scene The scene the eyes position is used from
  38860. */
  38861. MaterialHelper.BindEyePosition = function (effect, scene) {
  38862. if (scene._forcedViewPosition) {
  38863. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38864. return;
  38865. }
  38866. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38867. };
  38868. /**
  38869. * Helps preparing the defines values about the UVs in used in the effect.
  38870. * UVs are shared as much as we can accross chanels in the shaders.
  38871. * @param texture The texture we are preparing the UVs for
  38872. * @param defines The defines to update
  38873. * @param key The chanel key "diffuse", "specular"... used in the shader
  38874. */
  38875. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38876. defines._needUVs = true;
  38877. defines[key] = true;
  38878. if (texture.getTextureMatrix().isIdentity(true)) {
  38879. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38880. if (texture.coordinatesIndex === 0) {
  38881. defines["MAINUV1"] = true;
  38882. }
  38883. else {
  38884. defines["MAINUV2"] = true;
  38885. }
  38886. }
  38887. else {
  38888. defines[key + "DIRECTUV"] = 0;
  38889. }
  38890. };
  38891. /**
  38892. * Binds a texture matrix value to its corrsponding uniform
  38893. * @param texture The texture to bind the matrix for
  38894. * @param uniformBuffer The uniform buffer receivin the data
  38895. * @param key The chanel key "diffuse", "specular"... used in the shader
  38896. */
  38897. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38898. var matrix = texture.getTextureMatrix();
  38899. if (!matrix.isIdentity(true)) {
  38900. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38901. }
  38902. };
  38903. /**
  38904. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38905. * @param mesh defines the current mesh
  38906. * @param scene defines the current scene
  38907. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38908. * @param pointsCloud defines if point cloud rendering has to be turned on
  38909. * @param fogEnabled defines if fog has to be turned on
  38910. * @param alphaTest defines if alpha testing has to be turned on
  38911. * @param defines defines the current list of defines
  38912. */
  38913. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38914. if (defines._areMiscDirty) {
  38915. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38916. defines["POINTSIZE"] = pointsCloud;
  38917. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38918. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38919. defines["ALPHATEST"] = alphaTest;
  38920. }
  38921. };
  38922. /**
  38923. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38924. * @param scene defines the current scene
  38925. * @param engine defines the current engine
  38926. * @param defines specifies the list of active defines
  38927. * @param useInstances defines if instances have to be turned on
  38928. * @param useClipPlane defines if clip plane have to be turned on
  38929. */
  38930. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38931. if (useClipPlane === void 0) { useClipPlane = null; }
  38932. var changed = false;
  38933. if (useClipPlane == null) {
  38934. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38935. }
  38936. if (defines["CLIPPLANE"] !== useClipPlane) {
  38937. defines["CLIPPLANE"] = useClipPlane;
  38938. changed = true;
  38939. }
  38940. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38941. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38942. changed = true;
  38943. }
  38944. if (defines["INSTANCES"] !== useInstances) {
  38945. defines["INSTANCES"] = useInstances;
  38946. changed = true;
  38947. }
  38948. if (changed) {
  38949. defines.markAsUnprocessed();
  38950. }
  38951. };
  38952. /**
  38953. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38954. * @param mesh The mesh containing the geometry data we will draw
  38955. * @param defines The defines to update
  38956. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38957. * @param useBones Precise whether bones should be used or not (override mesh info)
  38958. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38959. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38960. * @returns false if defines are considered not dirty and have not been checked
  38961. */
  38962. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38963. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38964. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38965. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38966. return false;
  38967. }
  38968. defines._normals = defines._needNormals;
  38969. defines._uvs = defines._needUVs;
  38970. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38971. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38972. defines["TANGENT"] = true;
  38973. }
  38974. if (defines._needUVs) {
  38975. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38976. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38977. }
  38978. else {
  38979. defines["UV1"] = false;
  38980. defines["UV2"] = false;
  38981. }
  38982. if (useVertexColor) {
  38983. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38984. defines["VERTEXCOLOR"] = hasVertexColors;
  38985. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38986. }
  38987. if (useBones) {
  38988. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38989. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38990. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38991. }
  38992. else {
  38993. defines["NUM_BONE_INFLUENCERS"] = 0;
  38994. defines["BonesPerMesh"] = 0;
  38995. }
  38996. }
  38997. if (useMorphTargets) {
  38998. var manager = mesh.morphTargetManager;
  38999. if (manager) {
  39000. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39001. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39002. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39003. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39004. }
  39005. else {
  39006. defines["MORPHTARGETS_TANGENT"] = false;
  39007. defines["MORPHTARGETS_NORMAL"] = false;
  39008. defines["MORPHTARGETS"] = false;
  39009. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39010. }
  39011. }
  39012. return true;
  39013. };
  39014. /**
  39015. * Prepares the defines related to the light information passed in parameter
  39016. * @param scene The scene we are intending to draw
  39017. * @param mesh The mesh the effect is compiling for
  39018. * @param defines The defines to update
  39019. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39020. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39021. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39022. * @returns true if normals will be required for the rest of the effect
  39023. */
  39024. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39025. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39026. if (disableLighting === void 0) { disableLighting = false; }
  39027. if (!defines._areLightsDirty) {
  39028. return defines._needNormals;
  39029. }
  39030. var lightIndex = 0;
  39031. var needNormals = false;
  39032. var needRebuild = false;
  39033. var lightmapMode = false;
  39034. var shadowEnabled = false;
  39035. var specularEnabled = false;
  39036. if (scene.lightsEnabled && !disableLighting) {
  39037. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39038. var light = _a[_i];
  39039. needNormals = true;
  39040. if (defines["LIGHT" + lightIndex] === undefined) {
  39041. needRebuild = true;
  39042. }
  39043. defines["LIGHT" + lightIndex] = true;
  39044. defines["SPOTLIGHT" + lightIndex] = false;
  39045. defines["HEMILIGHT" + lightIndex] = false;
  39046. defines["POINTLIGHT" + lightIndex] = false;
  39047. defines["DIRLIGHT" + lightIndex] = false;
  39048. var type;
  39049. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39050. type = "SPOTLIGHT" + lightIndex;
  39051. var spotLight = light;
  39052. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39053. }
  39054. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39055. type = "HEMILIGHT" + lightIndex;
  39056. }
  39057. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39058. type = "POINTLIGHT" + lightIndex;
  39059. }
  39060. else {
  39061. type = "DIRLIGHT" + lightIndex;
  39062. }
  39063. defines[type] = true;
  39064. // Specular
  39065. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39066. specularEnabled = true;
  39067. }
  39068. // Shadows
  39069. defines["SHADOW" + lightIndex] = false;
  39070. defines["SHADOWPCF" + lightIndex] = false;
  39071. defines["SHADOWPCSS" + lightIndex] = false;
  39072. defines["SHADOWPOISSON" + lightIndex] = false;
  39073. defines["SHADOWESM" + lightIndex] = false;
  39074. defines["SHADOWCUBE" + lightIndex] = false;
  39075. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39076. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39077. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39078. var shadowGenerator = light.getShadowGenerator();
  39079. if (shadowGenerator) {
  39080. shadowEnabled = true;
  39081. shadowGenerator.prepareDefines(defines, lightIndex);
  39082. }
  39083. }
  39084. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39085. lightmapMode = true;
  39086. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39087. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39088. }
  39089. else {
  39090. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39091. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39092. }
  39093. lightIndex++;
  39094. if (lightIndex === maxSimultaneousLights)
  39095. break;
  39096. }
  39097. }
  39098. defines["SPECULARTERM"] = specularEnabled;
  39099. defines["SHADOWS"] = shadowEnabled;
  39100. // Resetting all other lights if any
  39101. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39102. if (defines["LIGHT" + index] !== undefined) {
  39103. defines["LIGHT" + index] = false;
  39104. defines["HEMILIGHT" + lightIndex] = false;
  39105. defines["POINTLIGHT" + lightIndex] = false;
  39106. defines["DIRLIGHT" + lightIndex] = false;
  39107. defines["SPOTLIGHT" + lightIndex] = false;
  39108. defines["SHADOW" + lightIndex] = false;
  39109. }
  39110. }
  39111. var caps = scene.getEngine().getCaps();
  39112. if (defines["SHADOWFLOAT"] === undefined) {
  39113. needRebuild = true;
  39114. }
  39115. defines["SHADOWFLOAT"] = shadowEnabled &&
  39116. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39117. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39118. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39119. if (needRebuild) {
  39120. defines.rebuild();
  39121. }
  39122. return needNormals;
  39123. };
  39124. /**
  39125. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39126. * that won t be acctive due to defines being turned off.
  39127. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39128. * @param samplersList The samplers list
  39129. * @param defines The defines helping in the list generation
  39130. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39131. */
  39132. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39133. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39134. var uniformsList;
  39135. var uniformBuffersList = null;
  39136. if (uniformsListOrOptions.uniformsNames) {
  39137. var options = uniformsListOrOptions;
  39138. uniformsList = options.uniformsNames;
  39139. uniformBuffersList = options.uniformBuffersNames;
  39140. samplersList = options.samplers;
  39141. defines = options.defines;
  39142. maxSimultaneousLights = options.maxSimultaneousLights;
  39143. }
  39144. else {
  39145. uniformsList = uniformsListOrOptions;
  39146. if (!samplersList) {
  39147. samplersList = [];
  39148. }
  39149. }
  39150. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39151. if (!defines["LIGHT" + lightIndex]) {
  39152. break;
  39153. }
  39154. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39155. if (uniformBuffersList) {
  39156. uniformBuffersList.push("Light" + lightIndex);
  39157. }
  39158. samplersList.push("shadowSampler" + lightIndex);
  39159. samplersList.push("depthSampler" + lightIndex);
  39160. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39161. samplersList.push("projectionLightSampler" + lightIndex);
  39162. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39163. }
  39164. }
  39165. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39166. uniformsList.push("morphTargetInfluences");
  39167. }
  39168. };
  39169. /**
  39170. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39171. * @param defines The defines to update while falling back
  39172. * @param fallbacks The authorized effect fallbacks
  39173. * @param maxSimultaneousLights The maximum number of lights allowed
  39174. * @param rank the current rank of the Effect
  39175. * @returns The newly affected rank
  39176. */
  39177. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39178. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39179. if (rank === void 0) { rank = 0; }
  39180. var lightFallbackRank = 0;
  39181. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39182. if (!defines["LIGHT" + lightIndex]) {
  39183. break;
  39184. }
  39185. if (lightIndex > 0) {
  39186. lightFallbackRank = rank + lightIndex;
  39187. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39188. }
  39189. if (!defines["SHADOWS"]) {
  39190. if (defines["SHADOW" + lightIndex]) {
  39191. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39192. }
  39193. if (defines["SHADOWPCF" + lightIndex]) {
  39194. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39195. }
  39196. if (defines["SHADOWPCSS" + lightIndex]) {
  39197. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39198. }
  39199. if (defines["SHADOWPOISSON" + lightIndex]) {
  39200. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39201. }
  39202. if (defines["SHADOWESM" + lightIndex]) {
  39203. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39204. }
  39205. }
  39206. }
  39207. return lightFallbackRank++;
  39208. };
  39209. /**
  39210. * Prepares the list of attributes required for morph targets according to the effect defines.
  39211. * @param attribs The current list of supported attribs
  39212. * @param mesh The mesh to prepare the morph targets attributes for
  39213. * @param defines The current Defines of the effect
  39214. */
  39215. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39216. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39217. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39218. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39219. var manager = mesh.morphTargetManager;
  39220. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39221. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39222. for (var index = 0; index < influencers; index++) {
  39223. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39224. if (normal) {
  39225. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39226. }
  39227. if (tangent) {
  39228. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39229. }
  39230. if (attribs.length > maxAttributesCount) {
  39231. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39232. }
  39233. }
  39234. }
  39235. };
  39236. /**
  39237. * Prepares the list of attributes required for bones according to the effect defines.
  39238. * @param attribs The current list of supported attribs
  39239. * @param mesh The mesh to prepare the bones attributes for
  39240. * @param defines The current Defines of the effect
  39241. * @param fallbacks The current efffect fallback strategy
  39242. */
  39243. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39244. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39245. fallbacks.addCPUSkinningFallback(0, mesh);
  39246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39248. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39249. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39250. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39251. }
  39252. }
  39253. };
  39254. /**
  39255. * Prepares the list of attributes required for instances according to the effect defines.
  39256. * @param attribs The current list of supported attribs
  39257. * @param defines The current Defines of the effect
  39258. */
  39259. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39260. if (defines["INSTANCES"]) {
  39261. attribs.push("world0");
  39262. attribs.push("world1");
  39263. attribs.push("world2");
  39264. attribs.push("world3");
  39265. }
  39266. };
  39267. /**
  39268. * Binds the light shadow information to the effect for the given mesh.
  39269. * @param light The light containing the generator
  39270. * @param scene The scene the lights belongs to
  39271. * @param mesh The mesh we are binding the information to render
  39272. * @param lightIndex The light index in the effect used to render the mesh
  39273. * @param effect The effect we are binding the data to
  39274. */
  39275. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39276. if (light.shadowEnabled && mesh.receiveShadows) {
  39277. var shadowGenerator = light.getShadowGenerator();
  39278. if (shadowGenerator) {
  39279. shadowGenerator.bindShadowLight(lightIndex, effect);
  39280. }
  39281. }
  39282. };
  39283. /**
  39284. * Binds the light information to the effect.
  39285. * @param light The light containing the generator
  39286. * @param effect The effect we are binding the data to
  39287. * @param lightIndex The light index in the effect used to render
  39288. */
  39289. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39290. light.transferToEffect(effect, lightIndex + "");
  39291. };
  39292. /**
  39293. * Binds the lights information from the scene to the effect for the given mesh.
  39294. * @param scene The scene the lights belongs to
  39295. * @param mesh The mesh we are binding the information to render
  39296. * @param effect The effect we are binding the data to
  39297. * @param defines The generated defines for the effect
  39298. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39299. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39300. */
  39301. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39302. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39303. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39304. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39305. for (var i = 0; i < len; i++) {
  39306. var light = mesh._lightSources[i];
  39307. var iAsString = i.toString();
  39308. var scaledIntensity = light.getScaledIntensity();
  39309. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39310. MaterialHelper.BindLightProperties(light, effect, i);
  39311. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39312. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39313. if (defines["SPECULARTERM"]) {
  39314. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39315. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39316. }
  39317. // Shadows
  39318. if (scene.shadowsEnabled) {
  39319. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39320. }
  39321. light._uniformBuffer.update();
  39322. }
  39323. };
  39324. /**
  39325. * Binds the fog information from the scene to the effect for the given mesh.
  39326. * @param scene The scene the lights belongs to
  39327. * @param mesh The mesh we are binding the information to render
  39328. * @param effect The effect we are binding the data to
  39329. */
  39330. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39331. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39332. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39333. effect.setColor3("vFogColor", scene.fogColor);
  39334. }
  39335. };
  39336. /**
  39337. * Binds the bones information from the mesh to the effect.
  39338. * @param mesh The mesh we are binding the information to render
  39339. * @param effect The effect we are binding the data to
  39340. */
  39341. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39342. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39343. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39344. if (matrices && effect) {
  39345. effect.setMatrices("mBones", matrices);
  39346. }
  39347. }
  39348. };
  39349. /**
  39350. * Binds the morph targets information from the mesh to the effect.
  39351. * @param abstractMesh The mesh we are binding the information to render
  39352. * @param effect The effect we are binding the data to
  39353. */
  39354. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39355. var manager = abstractMesh.morphTargetManager;
  39356. if (!abstractMesh || !manager) {
  39357. return;
  39358. }
  39359. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39360. };
  39361. /**
  39362. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39363. * @param defines The generated defines used in the effect
  39364. * @param effect The effect we are binding the data to
  39365. * @param scene The scene we are willing to render with logarithmic scale for
  39366. */
  39367. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39368. if (defines["LOGARITHMICDEPTH"]) {
  39369. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39370. }
  39371. };
  39372. /**
  39373. * Binds the clip plane information from the scene to the effect.
  39374. * @param scene The scene the clip plane information are extracted from
  39375. * @param effect The effect we are binding the data to
  39376. */
  39377. MaterialHelper.BindClipPlane = function (effect, scene) {
  39378. if (scene.clipPlane) {
  39379. var clipPlane = scene.clipPlane;
  39380. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39381. }
  39382. };
  39383. return MaterialHelper;
  39384. }());
  39385. BABYLON.MaterialHelper = MaterialHelper;
  39386. })(BABYLON || (BABYLON = {}));
  39387. //# sourceMappingURL=babylon.materialHelper.js.map
  39388. "use strict";
  39389. var BABYLON;
  39390. (function (BABYLON) {
  39391. var PushMaterial = /** @class */ (function (_super) {
  39392. __extends(PushMaterial, _super);
  39393. function PushMaterial(name, scene) {
  39394. var _this = _super.call(this, name, scene) || this;
  39395. _this._normalMatrix = new BABYLON.Matrix();
  39396. _this.storeEffectOnSubMeshes = true;
  39397. return _this;
  39398. }
  39399. PushMaterial.prototype.getEffect = function () {
  39400. return this._activeEffect;
  39401. };
  39402. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39403. if (!mesh) {
  39404. return false;
  39405. }
  39406. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39407. return true;
  39408. }
  39409. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39410. };
  39411. /**
  39412. * Binds the given world matrix to the active effect
  39413. *
  39414. * @param world the matrix to bind
  39415. */
  39416. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39417. this._activeEffect.setMatrix("world", world);
  39418. };
  39419. /**
  39420. * Binds the given normal matrix to the active effect
  39421. *
  39422. * @param normalMatrix the matrix to bind
  39423. */
  39424. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39425. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39426. };
  39427. PushMaterial.prototype.bind = function (world, mesh) {
  39428. if (!mesh) {
  39429. return;
  39430. }
  39431. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39432. };
  39433. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39434. if (effect === void 0) { effect = null; }
  39435. _super.prototype._afterBind.call(this, mesh);
  39436. this.getScene()._cachedEffect = effect;
  39437. };
  39438. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39439. if (visibility === void 0) { visibility = 1; }
  39440. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39441. };
  39442. return PushMaterial;
  39443. }(BABYLON.Material));
  39444. BABYLON.PushMaterial = PushMaterial;
  39445. })(BABYLON || (BABYLON = {}));
  39446. //# sourceMappingURL=babylon.pushMaterial.js.map
  39447. "use strict";
  39448. var BABYLON;
  39449. (function (BABYLON) {
  39450. /** @ignore */
  39451. var StandardMaterialDefines = /** @class */ (function (_super) {
  39452. __extends(StandardMaterialDefines, _super);
  39453. function StandardMaterialDefines() {
  39454. var _this = _super.call(this) || this;
  39455. _this.MAINUV1 = false;
  39456. _this.MAINUV2 = false;
  39457. _this.DIFFUSE = false;
  39458. _this.DIFFUSEDIRECTUV = 0;
  39459. _this.AMBIENT = false;
  39460. _this.AMBIENTDIRECTUV = 0;
  39461. _this.OPACITY = false;
  39462. _this.OPACITYDIRECTUV = 0;
  39463. _this.OPACITYRGB = false;
  39464. _this.REFLECTION = false;
  39465. _this.EMISSIVE = false;
  39466. _this.EMISSIVEDIRECTUV = 0;
  39467. _this.SPECULAR = false;
  39468. _this.SPECULARDIRECTUV = 0;
  39469. _this.BUMP = false;
  39470. _this.BUMPDIRECTUV = 0;
  39471. _this.PARALLAX = false;
  39472. _this.PARALLAXOCCLUSION = false;
  39473. _this.SPECULAROVERALPHA = false;
  39474. _this.CLIPPLANE = false;
  39475. _this.ALPHATEST = false;
  39476. _this.DEPTHPREPASS = false;
  39477. _this.ALPHAFROMDIFFUSE = false;
  39478. _this.POINTSIZE = false;
  39479. _this.FOG = false;
  39480. _this.SPECULARTERM = false;
  39481. _this.DIFFUSEFRESNEL = false;
  39482. _this.OPACITYFRESNEL = false;
  39483. _this.REFLECTIONFRESNEL = false;
  39484. _this.REFRACTIONFRESNEL = false;
  39485. _this.EMISSIVEFRESNEL = false;
  39486. _this.FRESNEL = false;
  39487. _this.NORMAL = false;
  39488. _this.UV1 = false;
  39489. _this.UV2 = false;
  39490. _this.VERTEXCOLOR = false;
  39491. _this.VERTEXALPHA = false;
  39492. _this.NUM_BONE_INFLUENCERS = 0;
  39493. _this.BonesPerMesh = 0;
  39494. _this.INSTANCES = false;
  39495. _this.GLOSSINESS = false;
  39496. _this.ROUGHNESS = false;
  39497. _this.EMISSIVEASILLUMINATION = false;
  39498. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39499. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39500. _this.LIGHTMAP = false;
  39501. _this.LIGHTMAPDIRECTUV = 0;
  39502. _this.OBJECTSPACE_NORMALMAP = false;
  39503. _this.USELIGHTMAPASSHADOWMAP = false;
  39504. _this.REFLECTIONMAP_3D = false;
  39505. _this.REFLECTIONMAP_SPHERICAL = false;
  39506. _this.REFLECTIONMAP_PLANAR = false;
  39507. _this.REFLECTIONMAP_CUBIC = false;
  39508. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39509. _this.REFLECTIONMAP_PROJECTION = false;
  39510. _this.REFLECTIONMAP_SKYBOX = false;
  39511. _this.REFLECTIONMAP_EXPLICIT = false;
  39512. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39513. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39514. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39515. _this.INVERTCUBICMAP = false;
  39516. _this.LOGARITHMICDEPTH = false;
  39517. _this.REFRACTION = false;
  39518. _this.REFRACTIONMAP_3D = false;
  39519. _this.REFLECTIONOVERALPHA = false;
  39520. _this.TWOSIDEDLIGHTING = false;
  39521. _this.SHADOWFLOAT = false;
  39522. _this.MORPHTARGETS = false;
  39523. _this.MORPHTARGETS_NORMAL = false;
  39524. _this.MORPHTARGETS_TANGENT = false;
  39525. _this.NUM_MORPH_INFLUENCERS = 0;
  39526. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39527. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39528. _this.IMAGEPROCESSING = false;
  39529. _this.VIGNETTE = false;
  39530. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39531. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39532. _this.TONEMAPPING = false;
  39533. _this.CONTRAST = false;
  39534. _this.COLORCURVES = false;
  39535. _this.COLORGRADING = false;
  39536. _this.COLORGRADING3D = false;
  39537. _this.SAMPLER3DGREENDEPTH = false;
  39538. _this.SAMPLER3DBGRMAP = false;
  39539. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39540. _this.EXPOSURE = false;
  39541. _this.rebuild();
  39542. return _this;
  39543. }
  39544. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39545. var modes = [
  39546. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39547. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39548. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39549. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39550. ];
  39551. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39552. var mode = modes_1[_i];
  39553. this[mode] = (mode === modeToEnable);
  39554. }
  39555. };
  39556. return StandardMaterialDefines;
  39557. }(BABYLON.MaterialDefines));
  39558. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39559. var StandardMaterial = /** @class */ (function (_super) {
  39560. __extends(StandardMaterial, _super);
  39561. function StandardMaterial(name, scene) {
  39562. var _this = _super.call(this, name, scene) || this;
  39563. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39564. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39565. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39566. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39567. _this.specularPower = 64;
  39568. _this._useAlphaFromDiffuseTexture = false;
  39569. _this._useEmissiveAsIllumination = false;
  39570. _this._linkEmissiveWithDiffuse = false;
  39571. _this._useSpecularOverAlpha = false;
  39572. _this._useReflectionOverAlpha = false;
  39573. _this._disableLighting = false;
  39574. _this._useObjectSpaceNormalMap = false;
  39575. _this._useParallax = false;
  39576. _this._useParallaxOcclusion = false;
  39577. _this.parallaxScaleBias = 0.05;
  39578. _this._roughness = 0;
  39579. _this.indexOfRefraction = 0.98;
  39580. _this.invertRefractionY = true;
  39581. _this._useLightmapAsShadowmap = false;
  39582. _this._useReflectionFresnelFromSpecular = false;
  39583. _this._useGlossinessFromSpecularMapAlpha = false;
  39584. _this._maxSimultaneousLights = 4;
  39585. /**
  39586. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39587. */
  39588. _this._invertNormalMapX = false;
  39589. /**
  39590. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39591. */
  39592. _this._invertNormalMapY = false;
  39593. /**
  39594. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39595. */
  39596. _this._twoSidedLighting = false;
  39597. _this._renderTargets = new BABYLON.SmartArray(16);
  39598. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39599. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39600. // Setup the default processing configuration to the scene.
  39601. _this._attachImageProcessingConfiguration(null);
  39602. _this.getRenderTargetTextures = function () {
  39603. _this._renderTargets.reset();
  39604. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39605. _this._renderTargets.push(_this._reflectionTexture);
  39606. }
  39607. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39608. _this._renderTargets.push(_this._refractionTexture);
  39609. }
  39610. return _this._renderTargets;
  39611. };
  39612. return _this;
  39613. }
  39614. ;
  39615. ;
  39616. ;
  39617. ;
  39618. ;
  39619. ;
  39620. ;
  39621. ;
  39622. ;
  39623. ;
  39624. ;
  39625. ;
  39626. ;
  39627. ;
  39628. ;
  39629. ;
  39630. ;
  39631. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39632. /**
  39633. * Gets the image processing configuration used either in this material.
  39634. */
  39635. get: function () {
  39636. return this._imageProcessingConfiguration;
  39637. },
  39638. /**
  39639. * Sets the Default image processing configuration used either in the this material.
  39640. *
  39641. * If sets to null, the scene one is in use.
  39642. */
  39643. set: function (value) {
  39644. this._attachImageProcessingConfiguration(value);
  39645. // Ensure the effect will be rebuilt.
  39646. this._markAllSubMeshesAsTexturesDirty();
  39647. },
  39648. enumerable: true,
  39649. configurable: true
  39650. });
  39651. /**
  39652. * Attaches a new image processing configuration to the Standard Material.
  39653. * @param configuration
  39654. */
  39655. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39656. var _this = this;
  39657. if (configuration === this._imageProcessingConfiguration) {
  39658. return;
  39659. }
  39660. // Detaches observer.
  39661. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39662. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39663. }
  39664. // Pick the scene configuration if needed.
  39665. if (!configuration) {
  39666. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39667. }
  39668. else {
  39669. this._imageProcessingConfiguration = configuration;
  39670. }
  39671. // Attaches observer.
  39672. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39673. _this._markAllSubMeshesAsImageProcessingDirty();
  39674. });
  39675. };
  39676. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39677. /**
  39678. * Gets wether the color curves effect is enabled.
  39679. */
  39680. get: function () {
  39681. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39682. },
  39683. /**
  39684. * Sets wether the color curves effect is enabled.
  39685. */
  39686. set: function (value) {
  39687. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39688. },
  39689. enumerable: true,
  39690. configurable: true
  39691. });
  39692. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39693. /**
  39694. * Gets wether the color grading effect is enabled.
  39695. */
  39696. get: function () {
  39697. return this.imageProcessingConfiguration.colorGradingEnabled;
  39698. },
  39699. /**
  39700. * Gets wether the color grading effect is enabled.
  39701. */
  39702. set: function (value) {
  39703. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39704. },
  39705. enumerable: true,
  39706. configurable: true
  39707. });
  39708. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39709. /**
  39710. * Gets wether tonemapping is enabled or not.
  39711. */
  39712. get: function () {
  39713. return this._imageProcessingConfiguration.toneMappingEnabled;
  39714. },
  39715. /**
  39716. * Sets wether tonemapping is enabled or not
  39717. */
  39718. set: function (value) {
  39719. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39720. },
  39721. enumerable: true,
  39722. configurable: true
  39723. });
  39724. ;
  39725. ;
  39726. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39727. /**
  39728. * The camera exposure used on this material.
  39729. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39730. * This corresponds to a photographic exposure.
  39731. */
  39732. get: function () {
  39733. return this._imageProcessingConfiguration.exposure;
  39734. },
  39735. /**
  39736. * The camera exposure used on this material.
  39737. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39738. * This corresponds to a photographic exposure.
  39739. */
  39740. set: function (value) {
  39741. this._imageProcessingConfiguration.exposure = value;
  39742. },
  39743. enumerable: true,
  39744. configurable: true
  39745. });
  39746. ;
  39747. ;
  39748. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39749. /**
  39750. * Gets The camera contrast used on this material.
  39751. */
  39752. get: function () {
  39753. return this._imageProcessingConfiguration.contrast;
  39754. },
  39755. /**
  39756. * Sets The camera contrast used on this material.
  39757. */
  39758. set: function (value) {
  39759. this._imageProcessingConfiguration.contrast = value;
  39760. },
  39761. enumerable: true,
  39762. configurable: true
  39763. });
  39764. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39765. /**
  39766. * Gets the Color Grading 2D Lookup Texture.
  39767. */
  39768. get: function () {
  39769. return this._imageProcessingConfiguration.colorGradingTexture;
  39770. },
  39771. /**
  39772. * Sets the Color Grading 2D Lookup Texture.
  39773. */
  39774. set: function (value) {
  39775. this._imageProcessingConfiguration.colorGradingTexture = value;
  39776. },
  39777. enumerable: true,
  39778. configurable: true
  39779. });
  39780. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39781. /**
  39782. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39783. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39784. * 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;
  39785. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39786. */
  39787. get: function () {
  39788. return this._imageProcessingConfiguration.colorCurves;
  39789. },
  39790. /**
  39791. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39792. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39793. * 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;
  39794. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39795. */
  39796. set: function (value) {
  39797. this._imageProcessingConfiguration.colorCurves = value;
  39798. },
  39799. enumerable: true,
  39800. configurable: true
  39801. });
  39802. StandardMaterial.prototype.getClassName = function () {
  39803. return "StandardMaterial";
  39804. };
  39805. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39806. get: function () {
  39807. return this._useLogarithmicDepth;
  39808. },
  39809. set: function (value) {
  39810. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39811. this._markAllSubMeshesAsMiscDirty();
  39812. },
  39813. enumerable: true,
  39814. configurable: true
  39815. });
  39816. StandardMaterial.prototype.needAlphaBlending = function () {
  39817. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39818. };
  39819. StandardMaterial.prototype.needAlphaTesting = function () {
  39820. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39821. };
  39822. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39823. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39824. };
  39825. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39826. return this._diffuseTexture;
  39827. };
  39828. /**
  39829. * Child classes can use it to update shaders
  39830. */
  39831. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39832. if (useInstances === void 0) { useInstances = false; }
  39833. if (subMesh.effect && this.isFrozen) {
  39834. if (this._wasPreviouslyReady && subMesh.effect) {
  39835. return true;
  39836. }
  39837. }
  39838. if (!subMesh._materialDefines) {
  39839. subMesh._materialDefines = new StandardMaterialDefines();
  39840. }
  39841. var scene = this.getScene();
  39842. var defines = subMesh._materialDefines;
  39843. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39844. if (defines._renderId === scene.getRenderId()) {
  39845. return true;
  39846. }
  39847. }
  39848. var engine = scene.getEngine();
  39849. // Lights
  39850. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39851. // Textures
  39852. if (defines._areTexturesDirty) {
  39853. defines._needUVs = false;
  39854. defines.MAINUV1 = false;
  39855. defines.MAINUV2 = false;
  39856. if (scene.texturesEnabled) {
  39857. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39858. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39859. return false;
  39860. }
  39861. else {
  39862. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39863. }
  39864. }
  39865. else {
  39866. defines.DIFFUSE = false;
  39867. }
  39868. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39869. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39870. return false;
  39871. }
  39872. else {
  39873. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39874. }
  39875. }
  39876. else {
  39877. defines.AMBIENT = false;
  39878. }
  39879. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39880. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39881. return false;
  39882. }
  39883. else {
  39884. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39885. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39886. }
  39887. }
  39888. else {
  39889. defines.OPACITY = false;
  39890. }
  39891. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39892. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39893. return false;
  39894. }
  39895. else {
  39896. defines._needNormals = true;
  39897. defines.REFLECTION = true;
  39898. defines.ROUGHNESS = (this._roughness > 0);
  39899. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39900. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39901. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39902. switch (this._reflectionTexture.coordinatesMode) {
  39903. case BABYLON.Texture.CUBIC_MODE:
  39904. case BABYLON.Texture.INVCUBIC_MODE:
  39905. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39906. break;
  39907. case BABYLON.Texture.EXPLICIT_MODE:
  39908. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39909. break;
  39910. case BABYLON.Texture.PLANAR_MODE:
  39911. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39912. break;
  39913. case BABYLON.Texture.PROJECTION_MODE:
  39914. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39915. break;
  39916. case BABYLON.Texture.SKYBOX_MODE:
  39917. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39918. break;
  39919. case BABYLON.Texture.SPHERICAL_MODE:
  39920. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39921. break;
  39922. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39923. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39924. break;
  39925. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39926. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39927. break;
  39928. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39929. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39930. break;
  39931. }
  39932. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39933. }
  39934. }
  39935. else {
  39936. defines.REFLECTION = false;
  39937. }
  39938. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39939. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39940. return false;
  39941. }
  39942. else {
  39943. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39944. }
  39945. }
  39946. else {
  39947. defines.EMISSIVE = false;
  39948. }
  39949. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39950. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39951. return false;
  39952. }
  39953. else {
  39954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39955. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39956. }
  39957. }
  39958. else {
  39959. defines.LIGHTMAP = false;
  39960. }
  39961. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39962. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39963. return false;
  39964. }
  39965. else {
  39966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39967. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39968. }
  39969. }
  39970. else {
  39971. defines.SPECULAR = false;
  39972. }
  39973. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39974. // Bump texure can not be not blocking.
  39975. if (!this._bumpTexture.isReady()) {
  39976. return false;
  39977. }
  39978. else {
  39979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39980. defines.PARALLAX = this._useParallax;
  39981. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39982. }
  39983. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39984. }
  39985. else {
  39986. defines.BUMP = false;
  39987. }
  39988. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39989. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39990. return false;
  39991. }
  39992. else {
  39993. defines._needUVs = true;
  39994. defines.REFRACTION = true;
  39995. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39996. }
  39997. }
  39998. else {
  39999. defines.REFRACTION = false;
  40000. }
  40001. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40002. }
  40003. else {
  40004. defines.DIFFUSE = false;
  40005. defines.AMBIENT = false;
  40006. defines.OPACITY = false;
  40007. defines.REFLECTION = false;
  40008. defines.EMISSIVE = false;
  40009. defines.LIGHTMAP = false;
  40010. defines.BUMP = false;
  40011. defines.REFRACTION = false;
  40012. }
  40013. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40014. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40015. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40016. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40017. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40018. }
  40019. if (defines._areImageProcessingDirty) {
  40020. if (!this._imageProcessingConfiguration.isReady()) {
  40021. return false;
  40022. }
  40023. this._imageProcessingConfiguration.prepareDefines(defines);
  40024. }
  40025. if (defines._areFresnelDirty) {
  40026. if (StandardMaterial.FresnelEnabled) {
  40027. // Fresnel
  40028. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40029. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40030. this._reflectionFresnelParameters) {
  40031. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40032. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40033. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40034. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40035. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40036. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40037. defines._needNormals = true;
  40038. defines.FRESNEL = true;
  40039. }
  40040. }
  40041. else {
  40042. defines.FRESNEL = false;
  40043. }
  40044. }
  40045. // Misc.
  40046. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40047. // Attribs
  40048. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40049. // Values that need to be evaluated on every frame
  40050. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40051. // Get correct effect
  40052. if (defines.isDirty) {
  40053. defines.markAsProcessed();
  40054. scene.resetCachedMaterial();
  40055. // Fallbacks
  40056. var fallbacks = new BABYLON.EffectFallbacks();
  40057. if (defines.REFLECTION) {
  40058. fallbacks.addFallback(0, "REFLECTION");
  40059. }
  40060. if (defines.SPECULAR) {
  40061. fallbacks.addFallback(0, "SPECULAR");
  40062. }
  40063. if (defines.BUMP) {
  40064. fallbacks.addFallback(0, "BUMP");
  40065. }
  40066. if (defines.PARALLAX) {
  40067. fallbacks.addFallback(1, "PARALLAX");
  40068. }
  40069. if (defines.PARALLAXOCCLUSION) {
  40070. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40071. }
  40072. if (defines.SPECULAROVERALPHA) {
  40073. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40074. }
  40075. if (defines.FOG) {
  40076. fallbacks.addFallback(1, "FOG");
  40077. }
  40078. if (defines.POINTSIZE) {
  40079. fallbacks.addFallback(0, "POINTSIZE");
  40080. }
  40081. if (defines.LOGARITHMICDEPTH) {
  40082. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40083. }
  40084. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40085. if (defines.SPECULARTERM) {
  40086. fallbacks.addFallback(0, "SPECULARTERM");
  40087. }
  40088. if (defines.DIFFUSEFRESNEL) {
  40089. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40090. }
  40091. if (defines.OPACITYFRESNEL) {
  40092. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40093. }
  40094. if (defines.REFLECTIONFRESNEL) {
  40095. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40096. }
  40097. if (defines.EMISSIVEFRESNEL) {
  40098. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40099. }
  40100. if (defines.FRESNEL) {
  40101. fallbacks.addFallback(4, "FRESNEL");
  40102. }
  40103. //Attributes
  40104. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40105. if (defines.NORMAL) {
  40106. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40107. }
  40108. if (defines.UV1) {
  40109. attribs.push(BABYLON.VertexBuffer.UVKind);
  40110. }
  40111. if (defines.UV2) {
  40112. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40113. }
  40114. if (defines.VERTEXCOLOR) {
  40115. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40116. }
  40117. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40118. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40119. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40120. var shaderName = "default";
  40121. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40122. "vFogInfos", "vFogColor", "pointSize",
  40123. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40124. "mBones",
  40125. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40126. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40127. "vReflectionPosition", "vReflectionSize",
  40128. "logarithmicDepthConstant", "vTangentSpaceParams"
  40129. ];
  40130. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40131. var uniformBuffers = ["Material", "Scene"];
  40132. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40133. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40134. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40135. uniformsNames: uniforms,
  40136. uniformBuffersNames: uniformBuffers,
  40137. samplers: samplers,
  40138. defines: defines,
  40139. maxSimultaneousLights: this._maxSimultaneousLights
  40140. });
  40141. if (this.customShaderNameResolve) {
  40142. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40143. }
  40144. var join = defines.toString();
  40145. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40146. attributes: attribs,
  40147. uniformsNames: uniforms,
  40148. uniformBuffersNames: uniformBuffers,
  40149. samplers: samplers,
  40150. defines: join,
  40151. fallbacks: fallbacks,
  40152. onCompiled: this.onCompiled,
  40153. onError: this.onError,
  40154. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40155. }, engine), defines);
  40156. this.buildUniformLayout();
  40157. }
  40158. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40159. return false;
  40160. }
  40161. defines._renderId = scene.getRenderId();
  40162. this._wasPreviouslyReady = true;
  40163. return true;
  40164. };
  40165. StandardMaterial.prototype.buildUniformLayout = function () {
  40166. // Order is important !
  40167. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40168. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40169. this._uniformBuffer.addUniform("opacityParts", 4);
  40170. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40171. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40172. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40173. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40174. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40175. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40176. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40177. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40178. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40179. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40180. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40181. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40182. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40183. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40184. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40185. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40186. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40187. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40188. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40189. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40190. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40191. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40192. this._uniformBuffer.addUniform("specularMatrix", 16);
  40193. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40194. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40195. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40196. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40197. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40198. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40199. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40200. this._uniformBuffer.addUniform("pointSize", 1);
  40201. this._uniformBuffer.create();
  40202. };
  40203. StandardMaterial.prototype.unbind = function () {
  40204. if (this._activeEffect) {
  40205. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40206. this._activeEffect.setTexture("reflection2DSampler", null);
  40207. }
  40208. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40209. this._activeEffect.setTexture("refraction2DSampler", null);
  40210. }
  40211. }
  40212. _super.prototype.unbind.call(this);
  40213. };
  40214. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40215. var scene = this.getScene();
  40216. var defines = subMesh._materialDefines;
  40217. if (!defines) {
  40218. return;
  40219. }
  40220. var effect = subMesh.effect;
  40221. if (!effect) {
  40222. return;
  40223. }
  40224. this._activeEffect = effect;
  40225. // Matrices
  40226. this.bindOnlyWorldMatrix(world);
  40227. // Normal Matrix
  40228. if (defines.OBJECTSPACE_NORMALMAP) {
  40229. world.toNormalMatrix(this._normalMatrix);
  40230. this.bindOnlyNormalMatrix(this._normalMatrix);
  40231. }
  40232. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40233. // Bones
  40234. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40235. if (mustRebind) {
  40236. this._uniformBuffer.bindToEffect(effect, "Material");
  40237. this.bindViewProjection(effect);
  40238. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40239. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40240. // Fresnel
  40241. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40242. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40243. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40244. }
  40245. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40246. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40247. }
  40248. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40249. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40250. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40251. }
  40252. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40253. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40254. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40255. }
  40256. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40257. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40258. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40259. }
  40260. }
  40261. // Textures
  40262. if (scene.texturesEnabled) {
  40263. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40264. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40265. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40266. }
  40267. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40268. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40269. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40270. }
  40271. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40272. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40273. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40274. }
  40275. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40276. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40277. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40278. if (this._reflectionTexture.boundingBoxSize) {
  40279. var cubeTexture = this._reflectionTexture;
  40280. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40281. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40282. }
  40283. }
  40284. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40285. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40286. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40287. }
  40288. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40289. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40290. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40291. }
  40292. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40293. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40294. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40295. }
  40296. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40297. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40298. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40299. if (scene._mirroredCameraPosition) {
  40300. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40301. }
  40302. else {
  40303. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40304. }
  40305. }
  40306. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40307. var depth = 1.0;
  40308. if (!this._refractionTexture.isCube) {
  40309. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40310. if (this._refractionTexture.depth) {
  40311. depth = this._refractionTexture.depth;
  40312. }
  40313. }
  40314. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40315. }
  40316. }
  40317. // Point size
  40318. if (this.pointsCloud) {
  40319. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40320. }
  40321. if (defines.SPECULARTERM) {
  40322. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40323. }
  40324. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40325. // Diffuse
  40326. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40327. }
  40328. // Textures
  40329. if (scene.texturesEnabled) {
  40330. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40331. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40332. }
  40333. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40334. effect.setTexture("ambientSampler", this._ambientTexture);
  40335. }
  40336. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40337. effect.setTexture("opacitySampler", this._opacityTexture);
  40338. }
  40339. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40340. if (this._reflectionTexture.isCube) {
  40341. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40342. }
  40343. else {
  40344. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40345. }
  40346. }
  40347. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40348. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40349. }
  40350. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40351. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40352. }
  40353. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40354. effect.setTexture("specularSampler", this._specularTexture);
  40355. }
  40356. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40357. effect.setTexture("bumpSampler", this._bumpTexture);
  40358. }
  40359. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40360. var depth = 1.0;
  40361. if (this._refractionTexture.isCube) {
  40362. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40363. }
  40364. else {
  40365. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40366. }
  40367. }
  40368. }
  40369. // Clip plane
  40370. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40371. // Colors
  40372. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40373. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40374. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40375. }
  40376. if (mustRebind || !this.isFrozen) {
  40377. // Lights
  40378. if (scene.lightsEnabled && !this._disableLighting) {
  40379. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40380. }
  40381. // View
  40382. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40383. this.bindView(effect);
  40384. }
  40385. // Fog
  40386. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40387. // Morph targets
  40388. if (defines.NUM_MORPH_INFLUENCERS) {
  40389. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40390. }
  40391. // Log. depth
  40392. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40393. // image processing
  40394. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40395. this._imageProcessingConfiguration.bind(this._activeEffect);
  40396. }
  40397. }
  40398. this._uniformBuffer.update();
  40399. this._afterBind(mesh, this._activeEffect);
  40400. };
  40401. StandardMaterial.prototype.getAnimatables = function () {
  40402. var results = [];
  40403. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40404. results.push(this._diffuseTexture);
  40405. }
  40406. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40407. results.push(this._ambientTexture);
  40408. }
  40409. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40410. results.push(this._opacityTexture);
  40411. }
  40412. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40413. results.push(this._reflectionTexture);
  40414. }
  40415. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40416. results.push(this._emissiveTexture);
  40417. }
  40418. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40419. results.push(this._specularTexture);
  40420. }
  40421. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40422. results.push(this._bumpTexture);
  40423. }
  40424. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40425. results.push(this._lightmapTexture);
  40426. }
  40427. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40428. results.push(this._refractionTexture);
  40429. }
  40430. return results;
  40431. };
  40432. StandardMaterial.prototype.getActiveTextures = function () {
  40433. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40434. if (this._diffuseTexture) {
  40435. activeTextures.push(this._diffuseTexture);
  40436. }
  40437. if (this._ambientTexture) {
  40438. activeTextures.push(this._ambientTexture);
  40439. }
  40440. if (this._opacityTexture) {
  40441. activeTextures.push(this._opacityTexture);
  40442. }
  40443. if (this._reflectionTexture) {
  40444. activeTextures.push(this._reflectionTexture);
  40445. }
  40446. if (this._emissiveTexture) {
  40447. activeTextures.push(this._emissiveTexture);
  40448. }
  40449. if (this._specularTexture) {
  40450. activeTextures.push(this._specularTexture);
  40451. }
  40452. if (this._bumpTexture) {
  40453. activeTextures.push(this._bumpTexture);
  40454. }
  40455. if (this._lightmapTexture) {
  40456. activeTextures.push(this._lightmapTexture);
  40457. }
  40458. if (this._refractionTexture) {
  40459. activeTextures.push(this._refractionTexture);
  40460. }
  40461. return activeTextures;
  40462. };
  40463. StandardMaterial.prototype.hasTexture = function (texture) {
  40464. if (_super.prototype.hasTexture.call(this, texture)) {
  40465. return true;
  40466. }
  40467. if (this._diffuseTexture === texture) {
  40468. return true;
  40469. }
  40470. if (this._ambientTexture === texture) {
  40471. return true;
  40472. }
  40473. if (this._opacityTexture === texture) {
  40474. return true;
  40475. }
  40476. if (this._reflectionTexture === texture) {
  40477. return true;
  40478. }
  40479. if (this._emissiveTexture === texture) {
  40480. return true;
  40481. }
  40482. if (this._specularTexture === texture) {
  40483. return true;
  40484. }
  40485. if (this._bumpTexture === texture) {
  40486. return true;
  40487. }
  40488. if (this._lightmapTexture === texture) {
  40489. return true;
  40490. }
  40491. if (this._refractionTexture === texture) {
  40492. return true;
  40493. }
  40494. return false;
  40495. };
  40496. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40497. if (forceDisposeTextures) {
  40498. if (this._diffuseTexture) {
  40499. this._diffuseTexture.dispose();
  40500. }
  40501. if (this._ambientTexture) {
  40502. this._ambientTexture.dispose();
  40503. }
  40504. if (this._opacityTexture) {
  40505. this._opacityTexture.dispose();
  40506. }
  40507. if (this._reflectionTexture) {
  40508. this._reflectionTexture.dispose();
  40509. }
  40510. if (this._emissiveTexture) {
  40511. this._emissiveTexture.dispose();
  40512. }
  40513. if (this._specularTexture) {
  40514. this._specularTexture.dispose();
  40515. }
  40516. if (this._bumpTexture) {
  40517. this._bumpTexture.dispose();
  40518. }
  40519. if (this._lightmapTexture) {
  40520. this._lightmapTexture.dispose();
  40521. }
  40522. if (this._refractionTexture) {
  40523. this._refractionTexture.dispose();
  40524. }
  40525. }
  40526. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40527. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40528. }
  40529. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40530. };
  40531. StandardMaterial.prototype.clone = function (name) {
  40532. var _this = this;
  40533. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40534. result.name = name;
  40535. result.id = name;
  40536. return result;
  40537. };
  40538. StandardMaterial.prototype.serialize = function () {
  40539. return BABYLON.SerializationHelper.Serialize(this);
  40540. };
  40541. // Statics
  40542. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40543. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40544. };
  40545. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40546. get: function () {
  40547. return StandardMaterial._DiffuseTextureEnabled;
  40548. },
  40549. set: function (value) {
  40550. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40551. return;
  40552. }
  40553. StandardMaterial._DiffuseTextureEnabled = value;
  40554. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40555. },
  40556. enumerable: true,
  40557. configurable: true
  40558. });
  40559. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40560. get: function () {
  40561. return StandardMaterial._AmbientTextureEnabled;
  40562. },
  40563. set: function (value) {
  40564. if (StandardMaterial._AmbientTextureEnabled === value) {
  40565. return;
  40566. }
  40567. StandardMaterial._AmbientTextureEnabled = value;
  40568. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40569. },
  40570. enumerable: true,
  40571. configurable: true
  40572. });
  40573. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40574. get: function () {
  40575. return StandardMaterial._OpacityTextureEnabled;
  40576. },
  40577. set: function (value) {
  40578. if (StandardMaterial._OpacityTextureEnabled === value) {
  40579. return;
  40580. }
  40581. StandardMaterial._OpacityTextureEnabled = value;
  40582. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40588. get: function () {
  40589. return StandardMaterial._ReflectionTextureEnabled;
  40590. },
  40591. set: function (value) {
  40592. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40593. return;
  40594. }
  40595. StandardMaterial._ReflectionTextureEnabled = value;
  40596. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40597. },
  40598. enumerable: true,
  40599. configurable: true
  40600. });
  40601. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40602. get: function () {
  40603. return StandardMaterial._EmissiveTextureEnabled;
  40604. },
  40605. set: function (value) {
  40606. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40607. return;
  40608. }
  40609. StandardMaterial._EmissiveTextureEnabled = value;
  40610. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40611. },
  40612. enumerable: true,
  40613. configurable: true
  40614. });
  40615. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40616. get: function () {
  40617. return StandardMaterial._SpecularTextureEnabled;
  40618. },
  40619. set: function (value) {
  40620. if (StandardMaterial._SpecularTextureEnabled === value) {
  40621. return;
  40622. }
  40623. StandardMaterial._SpecularTextureEnabled = value;
  40624. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40625. },
  40626. enumerable: true,
  40627. configurable: true
  40628. });
  40629. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40630. get: function () {
  40631. return StandardMaterial._BumpTextureEnabled;
  40632. },
  40633. set: function (value) {
  40634. if (StandardMaterial._BumpTextureEnabled === value) {
  40635. return;
  40636. }
  40637. StandardMaterial._BumpTextureEnabled = value;
  40638. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40639. },
  40640. enumerable: true,
  40641. configurable: true
  40642. });
  40643. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40644. get: function () {
  40645. return StandardMaterial._LightmapTextureEnabled;
  40646. },
  40647. set: function (value) {
  40648. if (StandardMaterial._LightmapTextureEnabled === value) {
  40649. return;
  40650. }
  40651. StandardMaterial._LightmapTextureEnabled = value;
  40652. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40653. },
  40654. enumerable: true,
  40655. configurable: true
  40656. });
  40657. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40658. get: function () {
  40659. return StandardMaterial._RefractionTextureEnabled;
  40660. },
  40661. set: function (value) {
  40662. if (StandardMaterial._RefractionTextureEnabled === value) {
  40663. return;
  40664. }
  40665. StandardMaterial._RefractionTextureEnabled = value;
  40666. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40667. },
  40668. enumerable: true,
  40669. configurable: true
  40670. });
  40671. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40672. get: function () {
  40673. return StandardMaterial._ColorGradingTextureEnabled;
  40674. },
  40675. set: function (value) {
  40676. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40677. return;
  40678. }
  40679. StandardMaterial._ColorGradingTextureEnabled = value;
  40680. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40681. },
  40682. enumerable: true,
  40683. configurable: true
  40684. });
  40685. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40686. get: function () {
  40687. return StandardMaterial._FresnelEnabled;
  40688. },
  40689. set: function (value) {
  40690. if (StandardMaterial._FresnelEnabled === value) {
  40691. return;
  40692. }
  40693. StandardMaterial._FresnelEnabled = value;
  40694. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40695. },
  40696. enumerable: true,
  40697. configurable: true
  40698. });
  40699. // Flags used to enable or disable a type of texture for all Standard Materials
  40700. StandardMaterial._DiffuseTextureEnabled = true;
  40701. StandardMaterial._AmbientTextureEnabled = true;
  40702. StandardMaterial._OpacityTextureEnabled = true;
  40703. StandardMaterial._ReflectionTextureEnabled = true;
  40704. StandardMaterial._EmissiveTextureEnabled = true;
  40705. StandardMaterial._SpecularTextureEnabled = true;
  40706. StandardMaterial._BumpTextureEnabled = true;
  40707. StandardMaterial._LightmapTextureEnabled = true;
  40708. StandardMaterial._RefractionTextureEnabled = true;
  40709. StandardMaterial._ColorGradingTextureEnabled = true;
  40710. StandardMaterial._FresnelEnabled = true;
  40711. __decorate([
  40712. BABYLON.serializeAsTexture("diffuseTexture")
  40713. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40714. __decorate([
  40715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40716. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40717. __decorate([
  40718. BABYLON.serializeAsTexture("ambientTexture")
  40719. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40720. __decorate([
  40721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40722. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40723. __decorate([
  40724. BABYLON.serializeAsTexture("opacityTexture")
  40725. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40726. __decorate([
  40727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40728. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40729. __decorate([
  40730. BABYLON.serializeAsTexture("reflectionTexture")
  40731. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40732. __decorate([
  40733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40734. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40735. __decorate([
  40736. BABYLON.serializeAsTexture("emissiveTexture")
  40737. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40738. __decorate([
  40739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40740. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40741. __decorate([
  40742. BABYLON.serializeAsTexture("specularTexture")
  40743. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40744. __decorate([
  40745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40746. ], StandardMaterial.prototype, "specularTexture", void 0);
  40747. __decorate([
  40748. BABYLON.serializeAsTexture("bumpTexture")
  40749. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40750. __decorate([
  40751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40752. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40753. __decorate([
  40754. BABYLON.serializeAsTexture("lightmapTexture")
  40755. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40756. __decorate([
  40757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40758. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40759. __decorate([
  40760. BABYLON.serializeAsTexture("refractionTexture")
  40761. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40762. __decorate([
  40763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40764. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40765. __decorate([
  40766. BABYLON.serializeAsColor3("ambient")
  40767. ], StandardMaterial.prototype, "ambientColor", void 0);
  40768. __decorate([
  40769. BABYLON.serializeAsColor3("diffuse")
  40770. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40771. __decorate([
  40772. BABYLON.serializeAsColor3("specular")
  40773. ], StandardMaterial.prototype, "specularColor", void 0);
  40774. __decorate([
  40775. BABYLON.serializeAsColor3("emissive")
  40776. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40777. __decorate([
  40778. BABYLON.serialize()
  40779. ], StandardMaterial.prototype, "specularPower", void 0);
  40780. __decorate([
  40781. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40782. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40783. __decorate([
  40784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40785. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40786. __decorate([
  40787. BABYLON.serialize("useEmissiveAsIllumination")
  40788. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40789. __decorate([
  40790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40791. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40792. __decorate([
  40793. BABYLON.serialize("linkEmissiveWithDiffuse")
  40794. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40795. __decorate([
  40796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40797. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40798. __decorate([
  40799. BABYLON.serialize("useSpecularOverAlpha")
  40800. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40801. __decorate([
  40802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40803. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40804. __decorate([
  40805. BABYLON.serialize("useReflectionOverAlpha")
  40806. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40807. __decorate([
  40808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40809. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40810. __decorate([
  40811. BABYLON.serialize("disableLighting")
  40812. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40813. __decorate([
  40814. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40815. ], StandardMaterial.prototype, "disableLighting", void 0);
  40816. __decorate([
  40817. BABYLON.serialize("useObjectSpaceNormalMap")
  40818. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40819. __decorate([
  40820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40821. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40822. __decorate([
  40823. BABYLON.serialize("useParallax")
  40824. ], StandardMaterial.prototype, "_useParallax", void 0);
  40825. __decorate([
  40826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40827. ], StandardMaterial.prototype, "useParallax", void 0);
  40828. __decorate([
  40829. BABYLON.serialize("useParallaxOcclusion")
  40830. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40831. __decorate([
  40832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40833. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40834. __decorate([
  40835. BABYLON.serialize()
  40836. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40837. __decorate([
  40838. BABYLON.serialize("roughness")
  40839. ], StandardMaterial.prototype, "_roughness", void 0);
  40840. __decorate([
  40841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40842. ], StandardMaterial.prototype, "roughness", void 0);
  40843. __decorate([
  40844. BABYLON.serialize()
  40845. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40846. __decorate([
  40847. BABYLON.serialize()
  40848. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40849. __decorate([
  40850. BABYLON.serialize("useLightmapAsShadowmap")
  40851. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40852. __decorate([
  40853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40854. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40855. __decorate([
  40856. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40857. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40858. __decorate([
  40859. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40860. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40861. __decorate([
  40862. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40863. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40864. __decorate([
  40865. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40866. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40867. __decorate([
  40868. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40869. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40870. __decorate([
  40871. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40872. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40873. __decorate([
  40874. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40875. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40876. __decorate([
  40877. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40878. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40879. __decorate([
  40880. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40881. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40882. __decorate([
  40883. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40884. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40885. __decorate([
  40886. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40887. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40888. __decorate([
  40889. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40890. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40891. __decorate([
  40892. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40893. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40894. __decorate([
  40895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40896. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40897. __decorate([
  40898. BABYLON.serialize("maxSimultaneousLights")
  40899. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40900. __decorate([
  40901. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40902. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40903. __decorate([
  40904. BABYLON.serialize("invertNormalMapX")
  40905. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40906. __decorate([
  40907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40908. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40909. __decorate([
  40910. BABYLON.serialize("invertNormalMapY")
  40911. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40912. __decorate([
  40913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40914. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40915. __decorate([
  40916. BABYLON.serialize("twoSidedLighting")
  40917. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40918. __decorate([
  40919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40920. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40921. __decorate([
  40922. BABYLON.serialize()
  40923. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40924. return StandardMaterial;
  40925. }(BABYLON.PushMaterial));
  40926. BABYLON.StandardMaterial = StandardMaterial;
  40927. })(BABYLON || (BABYLON = {}));
  40928. //# sourceMappingURL=babylon.standardMaterial.js.map
  40929. "use strict";
  40930. var BABYLON;
  40931. (function (BABYLON) {
  40932. /**
  40933. * Manages the defines for the PBR Material.
  40934. */
  40935. var PBRMaterialDefines = /** @class */ (function (_super) {
  40936. __extends(PBRMaterialDefines, _super);
  40937. /**
  40938. * Initializes the PBR Material defines.
  40939. */
  40940. function PBRMaterialDefines() {
  40941. var _this = _super.call(this) || this;
  40942. _this.PBR = true;
  40943. _this.MAINUV1 = false;
  40944. _this.MAINUV2 = false;
  40945. _this.UV1 = false;
  40946. _this.UV2 = false;
  40947. _this.ALBEDO = false;
  40948. _this.ALBEDODIRECTUV = 0;
  40949. _this.VERTEXCOLOR = false;
  40950. _this.AMBIENT = false;
  40951. _this.AMBIENTDIRECTUV = 0;
  40952. _this.AMBIENTINGRAYSCALE = false;
  40953. _this.OPACITY = false;
  40954. _this.VERTEXALPHA = false;
  40955. _this.OPACITYDIRECTUV = 0;
  40956. _this.OPACITYRGB = false;
  40957. _this.ALPHATEST = false;
  40958. _this.DEPTHPREPASS = false;
  40959. _this.ALPHABLEND = false;
  40960. _this.ALPHAFROMALBEDO = false;
  40961. _this.ALPHATESTVALUE = "0.5";
  40962. _this.SPECULAROVERALPHA = false;
  40963. _this.RADIANCEOVERALPHA = false;
  40964. _this.ALPHAFRESNEL = false;
  40965. _this.LINEARALPHAFRESNEL = false;
  40966. _this.PREMULTIPLYALPHA = false;
  40967. _this.EMISSIVE = false;
  40968. _this.EMISSIVEDIRECTUV = 0;
  40969. _this.REFLECTIVITY = false;
  40970. _this.REFLECTIVITYDIRECTUV = 0;
  40971. _this.SPECULARTERM = false;
  40972. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40973. _this.MICROSURFACEAUTOMATIC = false;
  40974. _this.LODBASEDMICROSFURACE = false;
  40975. _this.MICROSURFACEMAP = false;
  40976. _this.MICROSURFACEMAPDIRECTUV = 0;
  40977. _this.METALLICWORKFLOW = false;
  40978. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40979. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40980. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40981. _this.AOSTOREINMETALMAPRED = false;
  40982. _this.ENVIRONMENTBRDF = false;
  40983. _this.NORMAL = false;
  40984. _this.TANGENT = false;
  40985. _this.BUMP = false;
  40986. _this.BUMPDIRECTUV = 0;
  40987. _this.OBJECTSPACE_NORMALMAP = false;
  40988. _this.PARALLAX = false;
  40989. _this.PARALLAXOCCLUSION = false;
  40990. _this.NORMALXYSCALE = true;
  40991. _this.LIGHTMAP = false;
  40992. _this.LIGHTMAPDIRECTUV = 0;
  40993. _this.USELIGHTMAPASSHADOWMAP = false;
  40994. _this.GAMMALIGHTMAP = false;
  40995. _this.REFLECTION = false;
  40996. _this.REFLECTIONMAP_3D = false;
  40997. _this.REFLECTIONMAP_SPHERICAL = false;
  40998. _this.REFLECTIONMAP_PLANAR = false;
  40999. _this.REFLECTIONMAP_CUBIC = false;
  41000. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41001. _this.REFLECTIONMAP_PROJECTION = false;
  41002. _this.REFLECTIONMAP_SKYBOX = false;
  41003. _this.REFLECTIONMAP_EXPLICIT = false;
  41004. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41005. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41006. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41007. _this.INVERTCUBICMAP = false;
  41008. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41009. _this.USESPHERICALINVERTEX = false;
  41010. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41011. _this.LODINREFLECTIONALPHA = false;
  41012. _this.GAMMAREFLECTION = false;
  41013. _this.RADIANCEOCCLUSION = false;
  41014. _this.HORIZONOCCLUSION = false;
  41015. _this.REFRACTION = false;
  41016. _this.REFRACTIONMAP_3D = false;
  41017. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41018. _this.LODINREFRACTIONALPHA = false;
  41019. _this.GAMMAREFRACTION = false;
  41020. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41021. _this.INSTANCES = false;
  41022. _this.NUM_BONE_INFLUENCERS = 0;
  41023. _this.BonesPerMesh = 0;
  41024. _this.NONUNIFORMSCALING = false;
  41025. _this.MORPHTARGETS = false;
  41026. _this.MORPHTARGETS_NORMAL = false;
  41027. _this.MORPHTARGETS_TANGENT = false;
  41028. _this.NUM_MORPH_INFLUENCERS = 0;
  41029. _this.IMAGEPROCESSING = false;
  41030. _this.VIGNETTE = false;
  41031. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41032. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41033. _this.TONEMAPPING = false;
  41034. _this.CONTRAST = false;
  41035. _this.COLORCURVES = false;
  41036. _this.COLORGRADING = false;
  41037. _this.COLORGRADING3D = false;
  41038. _this.SAMPLER3DGREENDEPTH = false;
  41039. _this.SAMPLER3DBGRMAP = false;
  41040. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41041. _this.EXPOSURE = false;
  41042. _this.USEPHYSICALLIGHTFALLOFF = false;
  41043. _this.TWOSIDEDLIGHTING = false;
  41044. _this.SHADOWFLOAT = false;
  41045. _this.CLIPPLANE = false;
  41046. _this.POINTSIZE = false;
  41047. _this.FOG = false;
  41048. _this.LOGARITHMICDEPTH = false;
  41049. _this.FORCENORMALFORWARD = false;
  41050. _this.UNLIT = false;
  41051. _this.rebuild();
  41052. return _this;
  41053. }
  41054. /**
  41055. * Resets the PBR Material defines.
  41056. */
  41057. PBRMaterialDefines.prototype.reset = function () {
  41058. _super.prototype.reset.call(this);
  41059. this.ALPHATESTVALUE = "0.5";
  41060. this.PBR = true;
  41061. };
  41062. return PBRMaterialDefines;
  41063. }(BABYLON.MaterialDefines));
  41064. /**
  41065. * The Physically based material base class of BJS.
  41066. *
  41067. * This offers the main features of a standard PBR material.
  41068. * For more information, please refer to the documentation :
  41069. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41070. */
  41071. var PBRBaseMaterial = /** @class */ (function (_super) {
  41072. __extends(PBRBaseMaterial, _super);
  41073. /**
  41074. * Instantiates a new PBRMaterial instance.
  41075. *
  41076. * @param name The material name
  41077. * @param scene The scene the material will be use in.
  41078. */
  41079. function PBRBaseMaterial(name, scene) {
  41080. var _this = _super.call(this, name, scene) || this;
  41081. /**
  41082. * Intensity of the direct lights e.g. the four lights available in your scene.
  41083. * This impacts both the direct diffuse and specular highlights.
  41084. */
  41085. _this._directIntensity = 1.0;
  41086. /**
  41087. * Intensity of the emissive part of the material.
  41088. * This helps controlling the emissive effect without modifying the emissive color.
  41089. */
  41090. _this._emissiveIntensity = 1.0;
  41091. /**
  41092. * Intensity of the environment e.g. how much the environment will light the object
  41093. * either through harmonics for rough material or through the refelction for shiny ones.
  41094. */
  41095. _this._environmentIntensity = 1.0;
  41096. /**
  41097. * This is a special control allowing the reduction of the specular highlights coming from the
  41098. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41099. */
  41100. _this._specularIntensity = 1.0;
  41101. /**
  41102. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41103. */
  41104. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41105. /**
  41106. * Debug Control allowing disabling the bump map on this material.
  41107. */
  41108. _this._disableBumpMap = false;
  41109. /**
  41110. * AKA Occlusion Texture Intensity in other nomenclature.
  41111. */
  41112. _this._ambientTextureStrength = 1.0;
  41113. /**
  41114. * The color of a material in ambient lighting.
  41115. */
  41116. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41117. /**
  41118. * AKA Diffuse Color in other nomenclature.
  41119. */
  41120. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41121. /**
  41122. * AKA Specular Color in other nomenclature.
  41123. */
  41124. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41125. /**
  41126. * The color applied when light is reflected from a material.
  41127. */
  41128. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41129. /**
  41130. * The color applied when light is emitted from a material.
  41131. */
  41132. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41133. /**
  41134. * AKA Glossiness in other nomenclature.
  41135. */
  41136. _this._microSurface = 0.9;
  41137. /**
  41138. * source material index of refraction (IOR)' / 'destination material IOR.
  41139. */
  41140. _this._indexOfRefraction = 0.66;
  41141. /**
  41142. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41143. */
  41144. _this._invertRefractionY = false;
  41145. /**
  41146. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41147. * Materials half opaque for instance using refraction could benefit from this control.
  41148. */
  41149. _this._linkRefractionWithTransparency = false;
  41150. /**
  41151. * Specifies that the material will use the light map as a show map.
  41152. */
  41153. _this._useLightmapAsShadowmap = false;
  41154. /**
  41155. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41156. * makes the reflect vector face the model (under horizon).
  41157. */
  41158. _this._useHorizonOcclusion = true;
  41159. /**
  41160. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41161. * too much the area relying on ambient texture to define their ambient occlusion.
  41162. */
  41163. _this._useRadianceOcclusion = true;
  41164. /**
  41165. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41166. */
  41167. _this._useAlphaFromAlbedoTexture = false;
  41168. /**
  41169. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41170. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41171. */
  41172. _this._useSpecularOverAlpha = true;
  41173. /**
  41174. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41175. */
  41176. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41177. /**
  41178. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41179. */
  41180. _this._useRoughnessFromMetallicTextureAlpha = true;
  41181. /**
  41182. * Specifies if the metallic texture contains the roughness information in its green channel.
  41183. */
  41184. _this._useRoughnessFromMetallicTextureGreen = false;
  41185. /**
  41186. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41187. */
  41188. _this._useMetallnessFromMetallicTextureBlue = false;
  41189. /**
  41190. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41191. */
  41192. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41193. /**
  41194. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41195. */
  41196. _this._useAmbientInGrayScale = false;
  41197. /**
  41198. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41199. * The material will try to infer what glossiness each pixel should be.
  41200. */
  41201. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41202. /**
  41203. * BJS is using an harcoded light falloff based on a manually sets up range.
  41204. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41205. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41206. */
  41207. _this._usePhysicalLightFalloff = true;
  41208. /**
  41209. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41210. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41211. */
  41212. _this._useRadianceOverAlpha = true;
  41213. /**
  41214. * Allows using an object space normal map (instead of tangent space).
  41215. */
  41216. _this._useObjectSpaceNormalMap = false;
  41217. /**
  41218. * Allows using the bump map in parallax mode.
  41219. */
  41220. _this._useParallax = false;
  41221. /**
  41222. * Allows using the bump map in parallax occlusion mode.
  41223. */
  41224. _this._useParallaxOcclusion = false;
  41225. /**
  41226. * Controls the scale bias of the parallax mode.
  41227. */
  41228. _this._parallaxScaleBias = 0.05;
  41229. /**
  41230. * If sets to true, disables all the lights affecting the material.
  41231. */
  41232. _this._disableLighting = false;
  41233. /**
  41234. * Number of Simultaneous lights allowed on the material.
  41235. */
  41236. _this._maxSimultaneousLights = 4;
  41237. /**
  41238. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41239. */
  41240. _this._invertNormalMapX = false;
  41241. /**
  41242. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41243. */
  41244. _this._invertNormalMapY = false;
  41245. /**
  41246. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41247. */
  41248. _this._twoSidedLighting = false;
  41249. /**
  41250. * Defines the alpha limits in alpha test mode.
  41251. */
  41252. _this._alphaCutOff = 0.4;
  41253. /**
  41254. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41255. */
  41256. _this._forceAlphaTest = false;
  41257. /**
  41258. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41259. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41260. */
  41261. _this._useAlphaFresnel = false;
  41262. /**
  41263. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41264. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41265. */
  41266. _this._useLinearAlphaFresnel = false;
  41267. /**
  41268. * The transparency mode of the material.
  41269. */
  41270. _this._transparencyMode = null;
  41271. /**
  41272. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41273. * from cos thetav and roughness:
  41274. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41275. */
  41276. _this._environmentBRDFTexture = null;
  41277. /**
  41278. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41279. */
  41280. _this._forceIrradianceInFragment = false;
  41281. /**
  41282. * Force normal to face away from face.
  41283. */
  41284. _this._forceNormalForward = false;
  41285. /**
  41286. * Stores the available render targets.
  41287. */
  41288. _this._renderTargets = new BABYLON.SmartArray(16);
  41289. /**
  41290. * Sets the global ambient color for the material used in lighting calculations.
  41291. */
  41292. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41293. /**
  41294. * If set to true, no lighting calculations will be applied.
  41295. */
  41296. _this._unlit = false;
  41297. // Setup the default processing configuration to the scene.
  41298. _this._attachImageProcessingConfiguration(null);
  41299. _this.getRenderTargetTextures = function () {
  41300. _this._renderTargets.reset();
  41301. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41302. _this._renderTargets.push(_this._reflectionTexture);
  41303. }
  41304. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41305. _this._renderTargets.push(_this._refractionTexture);
  41306. }
  41307. return _this._renderTargets;
  41308. };
  41309. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41310. return _this;
  41311. }
  41312. /**
  41313. * Attaches a new image processing configuration to the PBR Material.
  41314. * @param configuration
  41315. */
  41316. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41317. var _this = this;
  41318. if (configuration === this._imageProcessingConfiguration) {
  41319. return;
  41320. }
  41321. // Detaches observer.
  41322. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41323. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41324. }
  41325. // Pick the scene configuration if needed.
  41326. if (!configuration) {
  41327. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41328. }
  41329. else {
  41330. this._imageProcessingConfiguration = configuration;
  41331. }
  41332. // Attaches observer.
  41333. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41334. _this._markAllSubMeshesAsImageProcessingDirty();
  41335. });
  41336. };
  41337. /**
  41338. * Gets the name of the material class.
  41339. */
  41340. PBRBaseMaterial.prototype.getClassName = function () {
  41341. return "PBRBaseMaterial";
  41342. };
  41343. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41344. /**
  41345. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41346. */
  41347. get: function () {
  41348. return this._useLogarithmicDepth;
  41349. },
  41350. /**
  41351. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41352. */
  41353. set: function (value) {
  41354. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41355. },
  41356. enumerable: true,
  41357. configurable: true
  41358. });
  41359. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41360. /**
  41361. * Gets the current transparency mode.
  41362. */
  41363. get: function () {
  41364. return this._transparencyMode;
  41365. },
  41366. /**
  41367. * Sets the transparency mode of the material.
  41368. */
  41369. set: function (value) {
  41370. if (this._transparencyMode === value) {
  41371. return;
  41372. }
  41373. this._transparencyMode = value;
  41374. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41375. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41381. /**
  41382. * Returns true if alpha blending should be disabled.
  41383. */
  41384. get: function () {
  41385. return (this._linkRefractionWithTransparency ||
  41386. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41387. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41388. },
  41389. enumerable: true,
  41390. configurable: true
  41391. });
  41392. /**
  41393. * Specifies whether or not this material should be rendered in alpha blend mode.
  41394. */
  41395. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41396. if (this._disableAlphaBlending) {
  41397. return false;
  41398. }
  41399. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41400. };
  41401. /**
  41402. * Specifies if the mesh will require alpha blending.
  41403. * @param mesh - BJS mesh.
  41404. */
  41405. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41406. if (this._disableAlphaBlending) {
  41407. return false;
  41408. }
  41409. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41410. };
  41411. /**
  41412. * Specifies whether or not this material should be rendered in alpha test mode.
  41413. */
  41414. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41415. if (this._forceAlphaTest) {
  41416. return true;
  41417. }
  41418. if (this._linkRefractionWithTransparency) {
  41419. return false;
  41420. }
  41421. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41422. };
  41423. /**
  41424. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41425. */
  41426. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41427. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41428. };
  41429. /**
  41430. * Gets the texture used for the alpha test.
  41431. */
  41432. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41433. return this._albedoTexture;
  41434. };
  41435. /**
  41436. * Specifies that the submesh is ready to be used.
  41437. * @param mesh - BJS mesh.
  41438. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41439. * @param useInstances - Specifies that instances should be used.
  41440. * @returns - boolean indicating that the submesh is ready or not.
  41441. */
  41442. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41443. if (subMesh.effect && this.isFrozen) {
  41444. if (this._wasPreviouslyReady) {
  41445. return true;
  41446. }
  41447. }
  41448. if (!subMesh._materialDefines) {
  41449. subMesh._materialDefines = new PBRMaterialDefines();
  41450. }
  41451. var defines = subMesh._materialDefines;
  41452. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41453. if (defines._renderId === this.getScene().getRenderId()) {
  41454. return true;
  41455. }
  41456. }
  41457. var scene = this.getScene();
  41458. var engine = scene.getEngine();
  41459. if (defines._areTexturesDirty) {
  41460. if (scene.texturesEnabled) {
  41461. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41462. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41463. return false;
  41464. }
  41465. }
  41466. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41467. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41468. return false;
  41469. }
  41470. }
  41471. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41472. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41473. return false;
  41474. }
  41475. }
  41476. var reflectionTexture = this._getReflectionTexture();
  41477. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41478. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41479. return false;
  41480. }
  41481. }
  41482. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41483. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41484. return false;
  41485. }
  41486. }
  41487. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41488. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41489. return false;
  41490. }
  41491. }
  41492. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41493. if (this._metallicTexture) {
  41494. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41495. return false;
  41496. }
  41497. }
  41498. else if (this._reflectivityTexture) {
  41499. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41500. return false;
  41501. }
  41502. }
  41503. if (this._microSurfaceTexture) {
  41504. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41505. return false;
  41506. }
  41507. }
  41508. }
  41509. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41510. // Bump texture cannot be not blocking.
  41511. if (!this._bumpTexture.isReady()) {
  41512. return false;
  41513. }
  41514. }
  41515. var refractionTexture = this._getRefractionTexture();
  41516. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41517. if (!refractionTexture.isReadyOrNotBlocking()) {
  41518. return false;
  41519. }
  41520. }
  41521. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41522. // This is blocking.
  41523. if (!this._environmentBRDFTexture.isReady()) {
  41524. return false;
  41525. }
  41526. }
  41527. }
  41528. }
  41529. if (defines._areImageProcessingDirty) {
  41530. if (!this._imageProcessingConfiguration.isReady()) {
  41531. return false;
  41532. }
  41533. }
  41534. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41535. mesh.createNormals(true);
  41536. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41537. }
  41538. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41539. if (effect) {
  41540. scene.resetCachedMaterial();
  41541. subMesh.setEffect(effect, defines);
  41542. this.buildUniformLayout();
  41543. }
  41544. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41545. return false;
  41546. }
  41547. defines._renderId = scene.getRenderId();
  41548. this._wasPreviouslyReady = true;
  41549. return true;
  41550. };
  41551. /**
  41552. * Specifies if the material uses metallic roughness workflow.
  41553. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41554. */
  41555. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41556. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41557. return true;
  41558. }
  41559. return false;
  41560. };
  41561. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41562. if (onCompiled === void 0) { onCompiled = null; }
  41563. if (onError === void 0) { onError = null; }
  41564. if (useInstances === void 0) { useInstances = null; }
  41565. if (useClipPlane === void 0) { useClipPlane = null; }
  41566. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41567. if (!defines.isDirty) {
  41568. return null;
  41569. }
  41570. defines.markAsProcessed();
  41571. var scene = this.getScene();
  41572. var engine = scene.getEngine();
  41573. // Fallbacks
  41574. var fallbacks = new BABYLON.EffectFallbacks();
  41575. var fallbackRank = 0;
  41576. if (defines.USESPHERICALINVERTEX) {
  41577. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41578. }
  41579. if (defines.FOG) {
  41580. fallbacks.addFallback(fallbackRank, "FOG");
  41581. }
  41582. if (defines.POINTSIZE) {
  41583. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41584. }
  41585. if (defines.LOGARITHMICDEPTH) {
  41586. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41587. }
  41588. if (defines.PARALLAX) {
  41589. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41590. }
  41591. if (defines.PARALLAXOCCLUSION) {
  41592. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41593. }
  41594. if (defines.ENVIRONMENTBRDF) {
  41595. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41596. }
  41597. if (defines.TANGENT) {
  41598. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41599. }
  41600. if (defines.BUMP) {
  41601. fallbacks.addFallback(fallbackRank++, "BUMP");
  41602. }
  41603. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41604. if (defines.SPECULARTERM) {
  41605. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41606. }
  41607. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41608. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41609. }
  41610. if (defines.LIGHTMAP) {
  41611. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41612. }
  41613. if (defines.NORMAL) {
  41614. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41615. }
  41616. if (defines.AMBIENT) {
  41617. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41618. }
  41619. if (defines.EMISSIVE) {
  41620. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41621. }
  41622. if (defines.VERTEXCOLOR) {
  41623. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41624. }
  41625. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41626. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41627. }
  41628. if (defines.MORPHTARGETS) {
  41629. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41630. }
  41631. //Attributes
  41632. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41633. if (defines.NORMAL) {
  41634. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41635. }
  41636. if (defines.TANGENT) {
  41637. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41638. }
  41639. if (defines.UV1) {
  41640. attribs.push(BABYLON.VertexBuffer.UVKind);
  41641. }
  41642. if (defines.UV2) {
  41643. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41644. }
  41645. if (defines.VERTEXCOLOR) {
  41646. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41647. }
  41648. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41649. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41650. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41651. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41652. "vFogInfos", "vFogColor", "pointSize",
  41653. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41654. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41655. "mBones",
  41656. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41657. "vLightingIntensity",
  41658. "logarithmicDepthConstant",
  41659. "vSphericalX", "vSphericalY", "vSphericalZ",
  41660. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41661. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41662. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41663. "vTangentSpaceParams"
  41664. ];
  41665. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41666. "bumpSampler", "lightmapSampler", "opacitySampler",
  41667. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41668. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41669. "microSurfaceSampler", "environmentBrdfSampler"];
  41670. var uniformBuffers = ["Material", "Scene"];
  41671. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41672. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41673. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41674. uniformsNames: uniforms,
  41675. uniformBuffersNames: uniformBuffers,
  41676. samplers: samplers,
  41677. defines: defines,
  41678. maxSimultaneousLights: this._maxSimultaneousLights
  41679. });
  41680. var join = defines.toString();
  41681. return engine.createEffect("pbr", {
  41682. attributes: attribs,
  41683. uniformsNames: uniforms,
  41684. uniformBuffersNames: uniformBuffers,
  41685. samplers: samplers,
  41686. defines: join,
  41687. fallbacks: fallbacks,
  41688. onCompiled: onCompiled,
  41689. onError: onError,
  41690. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41691. }, engine);
  41692. };
  41693. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41694. if (useInstances === void 0) { useInstances = null; }
  41695. if (useClipPlane === void 0) { useClipPlane = null; }
  41696. var scene = this.getScene();
  41697. var engine = scene.getEngine();
  41698. // Lights
  41699. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41700. defines._needNormals = true;
  41701. // Textures
  41702. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41703. if (defines._areTexturesDirty) {
  41704. defines._needUVs = false;
  41705. if (scene.texturesEnabled) {
  41706. if (scene.getEngine().getCaps().textureLOD) {
  41707. defines.LODBASEDMICROSFURACE = true;
  41708. }
  41709. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41710. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41711. }
  41712. else {
  41713. defines.ALBEDO = false;
  41714. }
  41715. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41716. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41717. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41718. }
  41719. else {
  41720. defines.AMBIENT = false;
  41721. }
  41722. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41724. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41725. }
  41726. else {
  41727. defines.OPACITY = false;
  41728. }
  41729. var reflectionTexture = this._getReflectionTexture();
  41730. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41731. defines.REFLECTION = true;
  41732. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41733. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41734. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41735. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41736. defines.INVERTCUBICMAP = true;
  41737. }
  41738. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41739. switch (reflectionTexture.coordinatesMode) {
  41740. case BABYLON.Texture.CUBIC_MODE:
  41741. case BABYLON.Texture.INVCUBIC_MODE:
  41742. defines.REFLECTIONMAP_CUBIC = true;
  41743. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41744. break;
  41745. case BABYLON.Texture.EXPLICIT_MODE:
  41746. defines.REFLECTIONMAP_EXPLICIT = true;
  41747. break;
  41748. case BABYLON.Texture.PLANAR_MODE:
  41749. defines.REFLECTIONMAP_PLANAR = true;
  41750. break;
  41751. case BABYLON.Texture.PROJECTION_MODE:
  41752. defines.REFLECTIONMAP_PROJECTION = true;
  41753. break;
  41754. case BABYLON.Texture.SKYBOX_MODE:
  41755. defines.REFLECTIONMAP_SKYBOX = true;
  41756. break;
  41757. case BABYLON.Texture.SPHERICAL_MODE:
  41758. defines.REFLECTIONMAP_SPHERICAL = true;
  41759. break;
  41760. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41761. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41762. break;
  41763. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41764. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41765. break;
  41766. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41767. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41768. break;
  41769. }
  41770. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41771. if (reflectionTexture.sphericalPolynomial) {
  41772. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41773. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41774. defines.USESPHERICALINVERTEX = false;
  41775. }
  41776. else {
  41777. defines.USESPHERICALINVERTEX = true;
  41778. }
  41779. }
  41780. }
  41781. }
  41782. else {
  41783. defines.REFLECTION = false;
  41784. defines.REFLECTIONMAP_3D = false;
  41785. defines.REFLECTIONMAP_SPHERICAL = false;
  41786. defines.REFLECTIONMAP_PLANAR = false;
  41787. defines.REFLECTIONMAP_CUBIC = false;
  41788. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41789. defines.REFLECTIONMAP_PROJECTION = false;
  41790. defines.REFLECTIONMAP_SKYBOX = false;
  41791. defines.REFLECTIONMAP_EXPLICIT = false;
  41792. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41793. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41794. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41795. defines.INVERTCUBICMAP = false;
  41796. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41797. defines.USESPHERICALINVERTEX = false;
  41798. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41799. defines.LODINREFLECTIONALPHA = false;
  41800. defines.GAMMAREFLECTION = false;
  41801. }
  41802. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41803. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41804. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41805. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41806. }
  41807. else {
  41808. defines.LIGHTMAP = false;
  41809. }
  41810. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41812. }
  41813. else {
  41814. defines.EMISSIVE = false;
  41815. }
  41816. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41817. if (this._metallicTexture) {
  41818. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41819. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41820. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41821. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41822. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41823. }
  41824. else if (this._reflectivityTexture) {
  41825. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41826. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41827. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41828. }
  41829. else {
  41830. defines.REFLECTIVITY = false;
  41831. }
  41832. if (this._microSurfaceTexture) {
  41833. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41834. }
  41835. else {
  41836. defines.MICROSURFACEMAP = false;
  41837. }
  41838. }
  41839. else {
  41840. defines.REFLECTIVITY = false;
  41841. defines.MICROSURFACEMAP = false;
  41842. }
  41843. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41844. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41845. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41846. defines.PARALLAX = true;
  41847. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41848. }
  41849. else {
  41850. defines.PARALLAX = false;
  41851. }
  41852. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41853. }
  41854. else {
  41855. defines.BUMP = false;
  41856. }
  41857. var refractionTexture = this._getRefractionTexture();
  41858. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41859. defines.REFRACTION = true;
  41860. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41861. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41862. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41863. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41864. if (this._linkRefractionWithTransparency) {
  41865. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41866. }
  41867. }
  41868. else {
  41869. defines.REFRACTION = false;
  41870. }
  41871. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41872. defines.ENVIRONMENTBRDF = true;
  41873. }
  41874. else {
  41875. defines.ENVIRONMENTBRDF = false;
  41876. }
  41877. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41878. defines.ALPHAFROMALBEDO = true;
  41879. }
  41880. else {
  41881. defines.ALPHAFROMALBEDO = false;
  41882. }
  41883. }
  41884. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41885. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41886. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41887. if (!this.backFaceCulling && this._twoSidedLighting) {
  41888. defines.TWOSIDEDLIGHTING = true;
  41889. }
  41890. else {
  41891. defines.TWOSIDEDLIGHTING = false;
  41892. }
  41893. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41894. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41895. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41896. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41897. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41898. }
  41899. if (defines._areImageProcessingDirty) {
  41900. this._imageProcessingConfiguration.prepareDefines(defines);
  41901. }
  41902. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41903. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41904. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41905. // Misc.
  41906. if (defines._areMiscDirty) {
  41907. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41908. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41909. }
  41910. // Values that need to be evaluated on every frame
  41911. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41912. // Attribs
  41913. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41914. };
  41915. /**
  41916. * Force shader compilation
  41917. */
  41918. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41919. var _this = this;
  41920. var localOptions = __assign({ clipPlane: false }, options);
  41921. var defines = new PBRMaterialDefines();
  41922. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41923. if (effect.isReady()) {
  41924. if (onCompiled) {
  41925. onCompiled(this);
  41926. }
  41927. }
  41928. else {
  41929. effect.onCompileObservable.add(function () {
  41930. if (onCompiled) {
  41931. onCompiled(_this);
  41932. }
  41933. });
  41934. }
  41935. };
  41936. /**
  41937. * Initializes the uniform buffer layout for the shader.
  41938. */
  41939. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41940. // Order is important !
  41941. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41942. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41943. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41944. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41945. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41946. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41947. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41948. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41949. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41950. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41951. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41952. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41953. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41954. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41955. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41956. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41957. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41958. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41959. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41960. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41961. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41962. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41963. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41964. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41965. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41966. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41967. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41968. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41969. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41970. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41971. this._uniformBuffer.addUniform("pointSize", 1);
  41972. this._uniformBuffer.create();
  41973. };
  41974. /**
  41975. * Unbinds the textures.
  41976. */
  41977. PBRBaseMaterial.prototype.unbind = function () {
  41978. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41979. this._uniformBuffer.setTexture("reflectionSampler", null);
  41980. }
  41981. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41982. this._uniformBuffer.setTexture("refractionSampler", null);
  41983. }
  41984. _super.prototype.unbind.call(this);
  41985. };
  41986. /**
  41987. * Binds the submesh data.
  41988. * @param world - The world matrix.
  41989. * @param mesh - The BJS mesh.
  41990. * @param subMesh - A submesh of the BJS mesh.
  41991. */
  41992. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41993. var scene = this.getScene();
  41994. var defines = subMesh._materialDefines;
  41995. if (!defines) {
  41996. return;
  41997. }
  41998. var effect = subMesh.effect;
  41999. if (!effect) {
  42000. return;
  42001. }
  42002. this._activeEffect = effect;
  42003. // Matrices
  42004. this.bindOnlyWorldMatrix(world);
  42005. // Normal Matrix
  42006. if (defines.OBJECTSPACE_NORMALMAP) {
  42007. world.toNormalMatrix(this._normalMatrix);
  42008. this.bindOnlyNormalMatrix(this._normalMatrix);
  42009. }
  42010. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42011. // Bones
  42012. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42013. var reflectionTexture = null;
  42014. if (mustRebind) {
  42015. this._uniformBuffer.bindToEffect(effect, "Material");
  42016. this.bindViewProjection(effect);
  42017. reflectionTexture = this._getReflectionTexture();
  42018. var refractionTexture = this._getRefractionTexture();
  42019. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42020. // Texture uniforms
  42021. if (scene.texturesEnabled) {
  42022. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42023. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42024. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42025. }
  42026. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42027. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42028. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42029. }
  42030. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42031. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42032. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42033. }
  42034. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42035. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42036. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42037. if (reflectionTexture.boundingBoxSize) {
  42038. var cubeTexture = reflectionTexture;
  42039. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42040. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42041. }
  42042. var polynomials = reflectionTexture.sphericalPolynomial;
  42043. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42044. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42045. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42046. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42047. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42048. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42049. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42050. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42051. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42052. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42053. }
  42054. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42055. }
  42056. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42057. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42058. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42059. }
  42060. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42061. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42062. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42063. }
  42064. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42065. if (this._metallicTexture) {
  42066. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42067. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42068. }
  42069. else if (this._reflectivityTexture) {
  42070. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42071. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42072. }
  42073. if (this._microSurfaceTexture) {
  42074. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42075. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42076. }
  42077. }
  42078. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42079. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42080. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42081. if (scene._mirroredCameraPosition) {
  42082. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42083. }
  42084. else {
  42085. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42086. }
  42087. }
  42088. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42089. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42090. var depth = 1.0;
  42091. if (!refractionTexture.isCube) {
  42092. if (refractionTexture.depth) {
  42093. depth = refractionTexture.depth;
  42094. }
  42095. }
  42096. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42097. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42098. }
  42099. }
  42100. // Point size
  42101. if (this.pointsCloud) {
  42102. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42103. }
  42104. // Colors
  42105. if (defines.METALLICWORKFLOW) {
  42106. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42107. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42108. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42109. }
  42110. else {
  42111. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42112. }
  42113. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42114. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42115. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42116. // Misc
  42117. this._lightingInfos.x = this._directIntensity;
  42118. this._lightingInfos.y = this._emissiveIntensity;
  42119. this._lightingInfos.z = this._environmentIntensity;
  42120. this._lightingInfos.w = this._specularIntensity;
  42121. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42122. }
  42123. // Textures
  42124. if (scene.texturesEnabled) {
  42125. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42126. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42127. }
  42128. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42129. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42130. }
  42131. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42132. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42133. }
  42134. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42135. if (defines.LODBASEDMICROSFURACE) {
  42136. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42137. }
  42138. else {
  42139. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42140. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42141. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42142. }
  42143. }
  42144. if (defines.ENVIRONMENTBRDF) {
  42145. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42146. }
  42147. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42148. if (defines.LODBASEDMICROSFURACE) {
  42149. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42150. }
  42151. else {
  42152. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42153. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42154. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42155. }
  42156. }
  42157. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42158. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42159. }
  42160. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42161. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42162. }
  42163. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42164. if (this._metallicTexture) {
  42165. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42166. }
  42167. else if (this._reflectivityTexture) {
  42168. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42169. }
  42170. if (this._microSurfaceTexture) {
  42171. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42172. }
  42173. }
  42174. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42175. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42176. }
  42177. }
  42178. // Clip plane
  42179. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42180. // Colors
  42181. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42182. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42183. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42184. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42185. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42186. }
  42187. if (mustRebind || !this.isFrozen) {
  42188. // Lights
  42189. if (scene.lightsEnabled && !this._disableLighting) {
  42190. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42191. }
  42192. // View
  42193. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42194. this.bindView(effect);
  42195. }
  42196. // Fog
  42197. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42198. // Morph targets
  42199. if (defines.NUM_MORPH_INFLUENCERS) {
  42200. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42201. }
  42202. // image processing
  42203. this._imageProcessingConfiguration.bind(this._activeEffect);
  42204. // Log. depth
  42205. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42206. }
  42207. this._uniformBuffer.update();
  42208. this._afterBind(mesh);
  42209. };
  42210. /**
  42211. * Returns the animatable textures.
  42212. * @returns - Array of animatable textures.
  42213. */
  42214. PBRBaseMaterial.prototype.getAnimatables = function () {
  42215. var results = [];
  42216. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42217. results.push(this._albedoTexture);
  42218. }
  42219. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42220. results.push(this._ambientTexture);
  42221. }
  42222. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42223. results.push(this._opacityTexture);
  42224. }
  42225. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42226. results.push(this._reflectionTexture);
  42227. }
  42228. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42229. results.push(this._emissiveTexture);
  42230. }
  42231. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42232. results.push(this._metallicTexture);
  42233. }
  42234. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42235. results.push(this._reflectivityTexture);
  42236. }
  42237. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42238. results.push(this._bumpTexture);
  42239. }
  42240. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42241. results.push(this._lightmapTexture);
  42242. }
  42243. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42244. results.push(this._refractionTexture);
  42245. }
  42246. return results;
  42247. };
  42248. /**
  42249. * Returns the texture used for reflections.
  42250. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42251. */
  42252. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42253. if (this._reflectionTexture) {
  42254. return this._reflectionTexture;
  42255. }
  42256. return this.getScene().environmentTexture;
  42257. };
  42258. /**
  42259. * Returns the texture used for refraction or null if none is used.
  42260. * @returns - Refection texture if present. If no refraction texture and refraction
  42261. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42262. */
  42263. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42264. if (this._refractionTexture) {
  42265. return this._refractionTexture;
  42266. }
  42267. if (this._linkRefractionWithTransparency) {
  42268. return this.getScene().environmentTexture;
  42269. }
  42270. return null;
  42271. };
  42272. /**
  42273. * Disposes the resources of the material.
  42274. * @param forceDisposeEffect - Forces the disposal of effects.
  42275. * @param forceDisposeTextures - Forces the disposal of all textures.
  42276. */
  42277. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42278. if (forceDisposeTextures) {
  42279. if (this._albedoTexture) {
  42280. this._albedoTexture.dispose();
  42281. }
  42282. if (this._ambientTexture) {
  42283. this._ambientTexture.dispose();
  42284. }
  42285. if (this._opacityTexture) {
  42286. this._opacityTexture.dispose();
  42287. }
  42288. if (this._reflectionTexture) {
  42289. this._reflectionTexture.dispose();
  42290. }
  42291. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42292. this._environmentBRDFTexture.dispose();
  42293. }
  42294. if (this._emissiveTexture) {
  42295. this._emissiveTexture.dispose();
  42296. }
  42297. if (this._metallicTexture) {
  42298. this._metallicTexture.dispose();
  42299. }
  42300. if (this._reflectivityTexture) {
  42301. this._reflectivityTexture.dispose();
  42302. }
  42303. if (this._bumpTexture) {
  42304. this._bumpTexture.dispose();
  42305. }
  42306. if (this._lightmapTexture) {
  42307. this._lightmapTexture.dispose();
  42308. }
  42309. if (this._refractionTexture) {
  42310. this._refractionTexture.dispose();
  42311. }
  42312. }
  42313. this._renderTargets.dispose();
  42314. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42315. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42316. }
  42317. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42318. };
  42319. /**
  42320. * Stores the reflectivity values based on metallic roughness workflow.
  42321. */
  42322. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42323. __decorate([
  42324. BABYLON.serializeAsImageProcessingConfiguration()
  42325. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42326. __decorate([
  42327. BABYLON.serialize()
  42328. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42329. __decorate([
  42330. BABYLON.serialize()
  42331. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42332. return PBRBaseMaterial;
  42333. }(BABYLON.PushMaterial));
  42334. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42335. })(BABYLON || (BABYLON = {}));
  42336. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42337. "use strict";
  42338. var BABYLON;
  42339. (function (BABYLON) {
  42340. /**
  42341. * The Physically based simple base material of BJS.
  42342. *
  42343. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42344. * It is used as the base class for both the specGloss and metalRough conventions.
  42345. */
  42346. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42347. __extends(PBRBaseSimpleMaterial, _super);
  42348. /**
  42349. * Instantiates a new PBRMaterial instance.
  42350. *
  42351. * @param name The material name
  42352. * @param scene The scene the material will be use in.
  42353. */
  42354. function PBRBaseSimpleMaterial(name, scene) {
  42355. var _this = _super.call(this, name, scene) || this;
  42356. /**
  42357. * Number of Simultaneous lights allowed on the material.
  42358. */
  42359. _this.maxSimultaneousLights = 4;
  42360. /**
  42361. * If sets to true, disables all the lights affecting the material.
  42362. */
  42363. _this.disableLighting = false;
  42364. /**
  42365. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42366. */
  42367. _this.invertNormalMapX = false;
  42368. /**
  42369. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42370. */
  42371. _this.invertNormalMapY = false;
  42372. /**
  42373. * Emissivie color used to self-illuminate the model.
  42374. */
  42375. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42376. /**
  42377. * Occlusion Channel Strenght.
  42378. */
  42379. _this.occlusionStrength = 1.0;
  42380. _this.useLightmapAsShadowmap = false;
  42381. _this._useAlphaFromAlbedoTexture = true;
  42382. _this._useAmbientInGrayScale = true;
  42383. return _this;
  42384. }
  42385. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42386. /**
  42387. * Gets the current double sided mode.
  42388. */
  42389. get: function () {
  42390. return this._twoSidedLighting;
  42391. },
  42392. /**
  42393. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42394. */
  42395. set: function (value) {
  42396. if (this._twoSidedLighting === value) {
  42397. return;
  42398. }
  42399. this._twoSidedLighting = value;
  42400. this.backFaceCulling = !value;
  42401. this._markAllSubMeshesAsTexturesDirty();
  42402. },
  42403. enumerable: true,
  42404. configurable: true
  42405. });
  42406. /**
  42407. * Return the active textures of the material.
  42408. */
  42409. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42410. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42411. if (this.environmentTexture) {
  42412. activeTextures.push(this.environmentTexture);
  42413. }
  42414. if (this.normalTexture) {
  42415. activeTextures.push(this.normalTexture);
  42416. }
  42417. if (this.emissiveTexture) {
  42418. activeTextures.push(this.emissiveTexture);
  42419. }
  42420. if (this.occlusionTexture) {
  42421. activeTextures.push(this.occlusionTexture);
  42422. }
  42423. if (this.lightmapTexture) {
  42424. activeTextures.push(this.lightmapTexture);
  42425. }
  42426. return activeTextures;
  42427. };
  42428. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42429. if (_super.prototype.hasTexture.call(this, texture)) {
  42430. return true;
  42431. }
  42432. if (this.lightmapTexture === texture) {
  42433. return true;
  42434. }
  42435. return false;
  42436. };
  42437. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42438. return "PBRBaseSimpleMaterial";
  42439. };
  42440. __decorate([
  42441. BABYLON.serialize(),
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42443. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42447. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42448. __decorate([
  42449. BABYLON.serializeAsTexture(),
  42450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42451. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42452. __decorate([
  42453. BABYLON.serialize(),
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42456. __decorate([
  42457. BABYLON.serialize(),
  42458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42459. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42460. __decorate([
  42461. BABYLON.serializeAsTexture(),
  42462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42463. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42464. __decorate([
  42465. BABYLON.serializeAsColor3("emissive"),
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42468. __decorate([
  42469. BABYLON.serializeAsTexture(),
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42471. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42475. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42476. __decorate([
  42477. BABYLON.serializeAsTexture(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42479. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42480. __decorate([
  42481. BABYLON.serialize(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42483. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42484. __decorate([
  42485. BABYLON.serialize()
  42486. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42487. __decorate([
  42488. BABYLON.serializeAsTexture(),
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42490. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42491. __decorate([
  42492. BABYLON.serialize(),
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42494. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42495. return PBRBaseSimpleMaterial;
  42496. }(BABYLON.PBRBaseMaterial));
  42497. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42498. })(BABYLON || (BABYLON = {}));
  42499. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42500. "use strict";
  42501. var BABYLON;
  42502. (function (BABYLON) {
  42503. /**
  42504. * The Physically based material of BJS.
  42505. *
  42506. * This offers the main features of a standard PBR material.
  42507. * For more information, please refer to the documentation :
  42508. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42509. */
  42510. var PBRMaterial = /** @class */ (function (_super) {
  42511. __extends(PBRMaterial, _super);
  42512. /**
  42513. * Instantiates a new PBRMaterial instance.
  42514. *
  42515. * @param name The material name
  42516. * @param scene The scene the material will be use in.
  42517. */
  42518. function PBRMaterial(name, scene) {
  42519. var _this = _super.call(this, name, scene) || this;
  42520. /**
  42521. * Intensity of the direct lights e.g. the four lights available in your scene.
  42522. * This impacts both the direct diffuse and specular highlights.
  42523. */
  42524. _this.directIntensity = 1.0;
  42525. /**
  42526. * Intensity of the emissive part of the material.
  42527. * This helps controlling the emissive effect without modifying the emissive color.
  42528. */
  42529. _this.emissiveIntensity = 1.0;
  42530. /**
  42531. * Intensity of the environment e.g. how much the environment will light the object
  42532. * either through harmonics for rough material or through the refelction for shiny ones.
  42533. */
  42534. _this.environmentIntensity = 1.0;
  42535. /**
  42536. * This is a special control allowing the reduction of the specular highlights coming from the
  42537. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42538. */
  42539. _this.specularIntensity = 1.0;
  42540. /**
  42541. * Debug Control allowing disabling the bump map on this material.
  42542. */
  42543. _this.disableBumpMap = false;
  42544. /**
  42545. * AKA Occlusion Texture Intensity in other nomenclature.
  42546. */
  42547. _this.ambientTextureStrength = 1.0;
  42548. /**
  42549. * The color of a material in ambient lighting.
  42550. */
  42551. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42552. /**
  42553. * AKA Diffuse Color in other nomenclature.
  42554. */
  42555. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42556. /**
  42557. * AKA Specular Color in other nomenclature.
  42558. */
  42559. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42560. /**
  42561. * The color reflected from the material.
  42562. */
  42563. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42564. /**
  42565. * The color emitted from the material.
  42566. */
  42567. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42568. /**
  42569. * AKA Glossiness in other nomenclature.
  42570. */
  42571. _this.microSurface = 1.0;
  42572. /**
  42573. * source material index of refraction (IOR)' / 'destination material IOR.
  42574. */
  42575. _this.indexOfRefraction = 0.66;
  42576. /**
  42577. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42578. */
  42579. _this.invertRefractionY = false;
  42580. /**
  42581. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42582. * Materials half opaque for instance using refraction could benefit from this control.
  42583. */
  42584. _this.linkRefractionWithTransparency = false;
  42585. _this.useLightmapAsShadowmap = false;
  42586. /**
  42587. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42588. */
  42589. _this.useAlphaFromAlbedoTexture = false;
  42590. /**
  42591. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42592. */
  42593. _this.forceAlphaTest = false;
  42594. /**
  42595. * Defines the alpha limits in alpha test mode.
  42596. */
  42597. _this.alphaCutOff = 0.4;
  42598. /**
  42599. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42600. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42601. */
  42602. _this.useSpecularOverAlpha = true;
  42603. /**
  42604. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42605. */
  42606. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42607. /**
  42608. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42609. */
  42610. _this.useRoughnessFromMetallicTextureAlpha = true;
  42611. /**
  42612. * Specifies if the metallic texture contains the roughness information in its green channel.
  42613. */
  42614. _this.useRoughnessFromMetallicTextureGreen = false;
  42615. /**
  42616. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42617. */
  42618. _this.useMetallnessFromMetallicTextureBlue = false;
  42619. /**
  42620. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42621. */
  42622. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42623. /**
  42624. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42625. */
  42626. _this.useAmbientInGrayScale = false;
  42627. /**
  42628. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42629. * The material will try to infer what glossiness each pixel should be.
  42630. */
  42631. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42632. /**
  42633. * BJS is using an harcoded light falloff based on a manually sets up range.
  42634. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42635. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42636. */
  42637. _this.usePhysicalLightFalloff = true;
  42638. /**
  42639. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42640. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42641. */
  42642. _this.useRadianceOverAlpha = true;
  42643. /**
  42644. * Allows using an object space normal map (instead of tangent space).
  42645. */
  42646. _this.useObjectSpaceNormalMap = false;
  42647. /**
  42648. * Allows using the bump map in parallax mode.
  42649. */
  42650. _this.useParallax = false;
  42651. /**
  42652. * Allows using the bump map in parallax occlusion mode.
  42653. */
  42654. _this.useParallaxOcclusion = false;
  42655. /**
  42656. * Controls the scale bias of the parallax mode.
  42657. */
  42658. _this.parallaxScaleBias = 0.05;
  42659. /**
  42660. * If sets to true, disables all the lights affecting the material.
  42661. */
  42662. _this.disableLighting = false;
  42663. /**
  42664. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42665. */
  42666. _this.forceIrradianceInFragment = false;
  42667. /**
  42668. * Number of Simultaneous lights allowed on the material.
  42669. */
  42670. _this.maxSimultaneousLights = 4;
  42671. /**
  42672. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42673. */
  42674. _this.invertNormalMapX = false;
  42675. /**
  42676. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42677. */
  42678. _this.invertNormalMapY = false;
  42679. /**
  42680. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42681. */
  42682. _this.twoSidedLighting = false;
  42683. /**
  42684. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42685. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42686. */
  42687. _this.useAlphaFresnel = false;
  42688. /**
  42689. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42690. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42691. */
  42692. _this.useLinearAlphaFresnel = false;
  42693. /**
  42694. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42695. * And/Or occlude the blended part.
  42696. */
  42697. _this.environmentBRDFTexture = null;
  42698. /**
  42699. * Force normal to face away from face.
  42700. */
  42701. _this.forceNormalForward = false;
  42702. /**
  42703. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42704. * makes the reflect vector face the model (under horizon).
  42705. */
  42706. _this.useHorizonOcclusion = true;
  42707. /**
  42708. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42709. * too much the area relying on ambient texture to define their ambient occlusion.
  42710. */
  42711. _this.useRadianceOcclusion = true;
  42712. /**
  42713. * If set to true, no lighting calculations will be applied.
  42714. */
  42715. _this.unlit = false;
  42716. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42717. return _this;
  42718. }
  42719. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42720. /**
  42721. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42722. */
  42723. get: function () {
  42724. return this._PBRMATERIAL_OPAQUE;
  42725. },
  42726. enumerable: true,
  42727. configurable: true
  42728. });
  42729. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42730. /**
  42731. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42732. */
  42733. get: function () {
  42734. return this._PBRMATERIAL_ALPHATEST;
  42735. },
  42736. enumerable: true,
  42737. configurable: true
  42738. });
  42739. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42740. /**
  42741. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42742. */
  42743. get: function () {
  42744. return this._PBRMATERIAL_ALPHABLEND;
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42750. /**
  42751. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42752. * They are also discarded below the alpha cutoff threshold to improve performances.
  42753. */
  42754. get: function () {
  42755. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42756. },
  42757. enumerable: true,
  42758. configurable: true
  42759. });
  42760. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42761. /**
  42762. * Gets the image processing configuration used either in this material.
  42763. */
  42764. get: function () {
  42765. return this._imageProcessingConfiguration;
  42766. },
  42767. /**
  42768. * Sets the Default image processing configuration used either in the this material.
  42769. *
  42770. * If sets to null, the scene one is in use.
  42771. */
  42772. set: function (value) {
  42773. this._attachImageProcessingConfiguration(value);
  42774. // Ensure the effect will be rebuilt.
  42775. this._markAllSubMeshesAsTexturesDirty();
  42776. },
  42777. enumerable: true,
  42778. configurable: true
  42779. });
  42780. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42781. /**
  42782. * Gets wether the color curves effect is enabled.
  42783. */
  42784. get: function () {
  42785. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42786. },
  42787. /**
  42788. * Sets wether the color curves effect is enabled.
  42789. */
  42790. set: function (value) {
  42791. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42792. },
  42793. enumerable: true,
  42794. configurable: true
  42795. });
  42796. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42797. /**
  42798. * Gets wether the color grading effect is enabled.
  42799. */
  42800. get: function () {
  42801. return this.imageProcessingConfiguration.colorGradingEnabled;
  42802. },
  42803. /**
  42804. * Gets wether the color grading effect is enabled.
  42805. */
  42806. set: function (value) {
  42807. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42813. /**
  42814. * Gets wether tonemapping is enabled or not.
  42815. */
  42816. get: function () {
  42817. return this._imageProcessingConfiguration.toneMappingEnabled;
  42818. },
  42819. /**
  42820. * Sets wether tonemapping is enabled or not
  42821. */
  42822. set: function (value) {
  42823. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. ;
  42829. ;
  42830. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42831. /**
  42832. * The camera exposure used on this material.
  42833. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42834. * This corresponds to a photographic exposure.
  42835. */
  42836. get: function () {
  42837. return this._imageProcessingConfiguration.exposure;
  42838. },
  42839. /**
  42840. * The camera exposure used on this material.
  42841. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42842. * This corresponds to a photographic exposure.
  42843. */
  42844. set: function (value) {
  42845. this._imageProcessingConfiguration.exposure = value;
  42846. },
  42847. enumerable: true,
  42848. configurable: true
  42849. });
  42850. ;
  42851. ;
  42852. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42853. /**
  42854. * Gets The camera contrast used on this material.
  42855. */
  42856. get: function () {
  42857. return this._imageProcessingConfiguration.contrast;
  42858. },
  42859. /**
  42860. * Sets The camera contrast used on this material.
  42861. */
  42862. set: function (value) {
  42863. this._imageProcessingConfiguration.contrast = value;
  42864. },
  42865. enumerable: true,
  42866. configurable: true
  42867. });
  42868. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42869. /**
  42870. * Gets the Color Grading 2D Lookup Texture.
  42871. */
  42872. get: function () {
  42873. return this._imageProcessingConfiguration.colorGradingTexture;
  42874. },
  42875. /**
  42876. * Sets the Color Grading 2D Lookup Texture.
  42877. */
  42878. set: function (value) {
  42879. this._imageProcessingConfiguration.colorGradingTexture = value;
  42880. },
  42881. enumerable: true,
  42882. configurable: true
  42883. });
  42884. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42885. /**
  42886. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42887. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42888. * 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;
  42889. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42890. */
  42891. get: function () {
  42892. return this._imageProcessingConfiguration.colorCurves;
  42893. },
  42894. /**
  42895. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42896. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42897. * 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;
  42898. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42899. */
  42900. set: function (value) {
  42901. this._imageProcessingConfiguration.colorCurves = value;
  42902. },
  42903. enumerable: true,
  42904. configurable: true
  42905. });
  42906. /**
  42907. * Returns the name of this material class.
  42908. */
  42909. PBRMaterial.prototype.getClassName = function () {
  42910. return "PBRMaterial";
  42911. };
  42912. /**
  42913. * Returns an array of the actively used textures.
  42914. * @returns - Array of BaseTextures
  42915. */
  42916. PBRMaterial.prototype.getActiveTextures = function () {
  42917. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42918. if (this._albedoTexture) {
  42919. activeTextures.push(this._albedoTexture);
  42920. }
  42921. if (this._ambientTexture) {
  42922. activeTextures.push(this._ambientTexture);
  42923. }
  42924. if (this._opacityTexture) {
  42925. activeTextures.push(this._opacityTexture);
  42926. }
  42927. if (this._reflectionTexture) {
  42928. activeTextures.push(this._reflectionTexture);
  42929. }
  42930. if (this._emissiveTexture) {
  42931. activeTextures.push(this._emissiveTexture);
  42932. }
  42933. if (this._reflectivityTexture) {
  42934. activeTextures.push(this._reflectivityTexture);
  42935. }
  42936. if (this._metallicTexture) {
  42937. activeTextures.push(this._metallicTexture);
  42938. }
  42939. if (this._microSurfaceTexture) {
  42940. activeTextures.push(this._microSurfaceTexture);
  42941. }
  42942. if (this._bumpTexture) {
  42943. activeTextures.push(this._bumpTexture);
  42944. }
  42945. if (this._lightmapTexture) {
  42946. activeTextures.push(this._lightmapTexture);
  42947. }
  42948. if (this._refractionTexture) {
  42949. activeTextures.push(this._refractionTexture);
  42950. }
  42951. return activeTextures;
  42952. };
  42953. /**
  42954. * Checks to see if a texture is used in the material.
  42955. * @param texture - Base texture to use.
  42956. * @returns - Boolean specifying if a texture is used in the material.
  42957. */
  42958. PBRMaterial.prototype.hasTexture = function (texture) {
  42959. if (_super.prototype.hasTexture.call(this, texture)) {
  42960. return true;
  42961. }
  42962. if (this._albedoTexture === texture) {
  42963. return true;
  42964. }
  42965. if (this._ambientTexture === texture) {
  42966. return true;
  42967. }
  42968. if (this._opacityTexture === texture) {
  42969. return true;
  42970. }
  42971. if (this._reflectionTexture === texture) {
  42972. return true;
  42973. }
  42974. if (this._reflectivityTexture === texture) {
  42975. return true;
  42976. }
  42977. if (this._metallicTexture === texture) {
  42978. return true;
  42979. }
  42980. if (this._microSurfaceTexture === texture) {
  42981. return true;
  42982. }
  42983. if (this._bumpTexture === texture) {
  42984. return true;
  42985. }
  42986. if (this._lightmapTexture === texture) {
  42987. return true;
  42988. }
  42989. if (this._refractionTexture === texture) {
  42990. return true;
  42991. }
  42992. return false;
  42993. };
  42994. /**
  42995. * Makes a duplicate of the current material.
  42996. * @param name - name to use for the new material.
  42997. */
  42998. PBRMaterial.prototype.clone = function (name) {
  42999. var _this = this;
  43000. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43001. clone.id = name;
  43002. clone.name = name;
  43003. return clone;
  43004. };
  43005. /**
  43006. * Serializes this PBR Material.
  43007. * @returns - An object with the serialized material.
  43008. */
  43009. PBRMaterial.prototype.serialize = function () {
  43010. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43011. serializationObject.customType = "BABYLON.PBRMaterial";
  43012. return serializationObject;
  43013. };
  43014. // Statics
  43015. /**
  43016. * Parses a PBR Material from a serialized object.
  43017. * @param source - Serialized object.
  43018. * @param scene - BJS scene instance.
  43019. * @param rootUrl - url for the scene object
  43020. * @returns - PBRMaterial
  43021. */
  43022. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43023. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43024. };
  43025. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43026. /**
  43027. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43028. */
  43029. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43030. /**
  43031. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43032. */
  43033. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43034. /**
  43035. * 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.
  43036. * They are also discarded below the alpha cutoff threshold to improve performances.
  43037. */
  43038. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43039. __decorate([
  43040. BABYLON.serialize(),
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43042. ], PBRMaterial.prototype, "directIntensity", void 0);
  43043. __decorate([
  43044. BABYLON.serialize(),
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43047. __decorate([
  43048. BABYLON.serialize(),
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43051. __decorate([
  43052. BABYLON.serialize(),
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43054. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43055. __decorate([
  43056. BABYLON.serialize(),
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43059. __decorate([
  43060. BABYLON.serializeAsTexture(),
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43063. __decorate([
  43064. BABYLON.serializeAsTexture(),
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43067. __decorate([
  43068. BABYLON.serialize(),
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43071. __decorate([
  43072. BABYLON.serializeAsTexture(),
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43074. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43075. __decorate([
  43076. BABYLON.serializeAsTexture(),
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43079. __decorate([
  43080. BABYLON.serializeAsTexture(),
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43083. __decorate([
  43084. BABYLON.serializeAsTexture(),
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43086. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43087. __decorate([
  43088. BABYLON.serializeAsTexture(),
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43091. __decorate([
  43092. BABYLON.serialize(),
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43094. ], PBRMaterial.prototype, "metallic", void 0);
  43095. __decorate([
  43096. BABYLON.serialize(),
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], PBRMaterial.prototype, "roughness", void 0);
  43099. __decorate([
  43100. BABYLON.serializeAsTexture(),
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43103. __decorate([
  43104. BABYLON.serializeAsTexture(),
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43106. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43107. __decorate([
  43108. BABYLON.serializeAsTexture(),
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43110. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43111. __decorate([
  43112. BABYLON.serializeAsTexture(),
  43113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43114. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43115. __decorate([
  43116. BABYLON.serializeAsColor3("ambient"),
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], PBRMaterial.prototype, "ambientColor", void 0);
  43119. __decorate([
  43120. BABYLON.serializeAsColor3("albedo"),
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43122. ], PBRMaterial.prototype, "albedoColor", void 0);
  43123. __decorate([
  43124. BABYLON.serializeAsColor3("reflectivity"),
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43126. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43127. __decorate([
  43128. BABYLON.serializeAsColor3("reflection"),
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43130. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43131. __decorate([
  43132. BABYLON.serializeAsColor3("emissive"),
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43134. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43135. __decorate([
  43136. BABYLON.serialize(),
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], PBRMaterial.prototype, "microSurface", void 0);
  43139. __decorate([
  43140. BABYLON.serialize(),
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43143. __decorate([
  43144. BABYLON.serialize(),
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43146. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43147. __decorate([
  43148. BABYLON.serialize(),
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43151. __decorate([
  43152. BABYLON.serialize(),
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43155. __decorate([
  43156. BABYLON.serialize(),
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43158. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43159. __decorate([
  43160. BABYLON.serialize(),
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43162. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43163. __decorate([
  43164. BABYLON.serialize(),
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43166. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43167. __decorate([
  43168. BABYLON.serialize(),
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43170. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43171. __decorate([
  43172. BABYLON.serialize(),
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43175. __decorate([
  43176. BABYLON.serialize(),
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43178. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43179. __decorate([
  43180. BABYLON.serialize(),
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43182. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43183. __decorate([
  43184. BABYLON.serialize(),
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43187. __decorate([
  43188. BABYLON.serialize(),
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43190. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43191. __decorate([
  43192. BABYLON.serialize(),
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43195. __decorate([
  43196. BABYLON.serialize(),
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43198. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43199. __decorate([
  43200. BABYLON.serialize(),
  43201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43202. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43203. __decorate([
  43204. BABYLON.serialize(),
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43207. __decorate([
  43208. BABYLON.serialize(),
  43209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43210. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43211. __decorate([
  43212. BABYLON.serialize(),
  43213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43214. ], PBRMaterial.prototype, "useParallax", void 0);
  43215. __decorate([
  43216. BABYLON.serialize(),
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43219. __decorate([
  43220. BABYLON.serialize(),
  43221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43222. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43223. __decorate([
  43224. BABYLON.serialize(),
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43226. ], PBRMaterial.prototype, "disableLighting", void 0);
  43227. __decorate([
  43228. BABYLON.serialize(),
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43231. __decorate([
  43232. BABYLON.serialize(),
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43234. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43235. __decorate([
  43236. BABYLON.serialize(),
  43237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43238. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43239. __decorate([
  43240. BABYLON.serialize(),
  43241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43242. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43243. __decorate([
  43244. BABYLON.serialize(),
  43245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43246. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43247. __decorate([
  43248. BABYLON.serialize(),
  43249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43250. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43251. __decorate([
  43252. BABYLON.serialize(),
  43253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43254. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43255. __decorate([
  43256. BABYLON.serializeAsTexture(),
  43257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43258. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43259. __decorate([
  43260. BABYLON.serialize(),
  43261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43262. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43263. __decorate([
  43264. BABYLON.serialize(),
  43265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43266. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43267. __decorate([
  43268. BABYLON.serialize(),
  43269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43270. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43271. __decorate([
  43272. BABYLON.serialize(),
  43273. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43274. ], PBRMaterial.prototype, "unlit", void 0);
  43275. return PBRMaterial;
  43276. }(BABYLON.PBRBaseMaterial));
  43277. BABYLON.PBRMaterial = PBRMaterial;
  43278. })(BABYLON || (BABYLON = {}));
  43279. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43280. "use strict";
  43281. var BABYLON;
  43282. (function (BABYLON) {
  43283. /**
  43284. * The PBR material of BJS following the metal roughness convention.
  43285. *
  43286. * This fits to the PBR convention in the GLTF definition:
  43287. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43288. */
  43289. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43290. __extends(PBRMetallicRoughnessMaterial, _super);
  43291. /**
  43292. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43293. *
  43294. * @param name The material name
  43295. * @param scene The scene the material will be use in.
  43296. */
  43297. function PBRMetallicRoughnessMaterial(name, scene) {
  43298. var _this = _super.call(this, name, scene) || this;
  43299. _this._useRoughnessFromMetallicTextureAlpha = false;
  43300. _this._useRoughnessFromMetallicTextureGreen = true;
  43301. _this._useMetallnessFromMetallicTextureBlue = true;
  43302. _this.metallic = 1.0;
  43303. _this.roughness = 1.0;
  43304. return _this;
  43305. }
  43306. /**
  43307. * Return the currrent class name of the material.
  43308. */
  43309. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43310. return "PBRMetallicRoughnessMaterial";
  43311. };
  43312. /**
  43313. * Return the active textures of the material.
  43314. */
  43315. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43316. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43317. if (this.baseTexture) {
  43318. activeTextures.push(this.baseTexture);
  43319. }
  43320. if (this.metallicRoughnessTexture) {
  43321. activeTextures.push(this.metallicRoughnessTexture);
  43322. }
  43323. return activeTextures;
  43324. };
  43325. /**
  43326. * Checks to see if a texture is used in the material.
  43327. * @param texture - Base texture to use.
  43328. * @returns - Boolean specifying if a texture is used in the material.
  43329. */
  43330. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43331. if (_super.prototype.hasTexture.call(this, texture)) {
  43332. return true;
  43333. }
  43334. if (this.baseTexture === texture) {
  43335. return true;
  43336. }
  43337. if (this.metallicRoughnessTexture === texture) {
  43338. return true;
  43339. }
  43340. return false;
  43341. };
  43342. /**
  43343. * Makes a duplicate of the current material.
  43344. * @param name - name to use for the new material.
  43345. */
  43346. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43347. var _this = this;
  43348. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43349. clone.id = name;
  43350. clone.name = name;
  43351. return clone;
  43352. };
  43353. /**
  43354. * Serialize the material to a parsable JSON object.
  43355. */
  43356. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43358. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43359. return serializationObject;
  43360. };
  43361. /**
  43362. * Parses a JSON object correponding to the serialize function.
  43363. */
  43364. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43365. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43366. };
  43367. __decorate([
  43368. BABYLON.serializeAsColor3(),
  43369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43370. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43371. __decorate([
  43372. BABYLON.serializeAsTexture(),
  43373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43374. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43375. __decorate([
  43376. BABYLON.serialize(),
  43377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43378. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43379. __decorate([
  43380. BABYLON.serialize(),
  43381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43382. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43383. __decorate([
  43384. BABYLON.serializeAsTexture(),
  43385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43386. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43387. return PBRMetallicRoughnessMaterial;
  43388. }(BABYLON.PBRBaseSimpleMaterial));
  43389. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43390. })(BABYLON || (BABYLON = {}));
  43391. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43392. "use strict";
  43393. var BABYLON;
  43394. (function (BABYLON) {
  43395. /**
  43396. * The PBR material of BJS following the specular glossiness convention.
  43397. *
  43398. * This fits to the PBR convention in the GLTF definition:
  43399. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43400. */
  43401. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43402. __extends(PBRSpecularGlossinessMaterial, _super);
  43403. /**
  43404. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43405. *
  43406. * @param name The material name
  43407. * @param scene The scene the material will be use in.
  43408. */
  43409. function PBRSpecularGlossinessMaterial(name, scene) {
  43410. var _this = _super.call(this, name, scene) || this;
  43411. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43412. return _this;
  43413. }
  43414. /**
  43415. * Return the currrent class name of the material.
  43416. */
  43417. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43418. return "PBRSpecularGlossinessMaterial";
  43419. };
  43420. /**
  43421. * Return the active textures of the material.
  43422. */
  43423. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43424. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43425. if (this.diffuseTexture) {
  43426. activeTextures.push(this.diffuseTexture);
  43427. }
  43428. if (this.specularGlossinessTexture) {
  43429. activeTextures.push(this.specularGlossinessTexture);
  43430. }
  43431. return activeTextures;
  43432. };
  43433. /**
  43434. * Checks to see if a texture is used in the material.
  43435. * @param texture - Base texture to use.
  43436. * @returns - Boolean specifying if a texture is used in the material.
  43437. */
  43438. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43439. if (_super.prototype.hasTexture.call(this, texture)) {
  43440. return true;
  43441. }
  43442. if (this.diffuseTexture === texture) {
  43443. return true;
  43444. }
  43445. if (this.specularGlossinessTexture === texture) {
  43446. return true;
  43447. }
  43448. return false;
  43449. };
  43450. /**
  43451. * Makes a duplicate of the current material.
  43452. * @param name - name to use for the new material.
  43453. */
  43454. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43455. var _this = this;
  43456. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43457. clone.id = name;
  43458. clone.name = name;
  43459. return clone;
  43460. };
  43461. /**
  43462. * Serialize the material to a parsable JSON object.
  43463. */
  43464. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43465. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43466. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43467. return serializationObject;
  43468. };
  43469. /**
  43470. * Parses a JSON object correponding to the serialize function.
  43471. */
  43472. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43473. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43474. };
  43475. __decorate([
  43476. BABYLON.serializeAsColor3("diffuse"),
  43477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43478. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43479. __decorate([
  43480. BABYLON.serializeAsTexture(),
  43481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43482. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43483. __decorate([
  43484. BABYLON.serializeAsColor3("specular"),
  43485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43486. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43487. __decorate([
  43488. BABYLON.serialize(),
  43489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43490. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43491. __decorate([
  43492. BABYLON.serializeAsTexture(),
  43493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43494. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43495. return PBRSpecularGlossinessMaterial;
  43496. }(BABYLON.PBRBaseSimpleMaterial));
  43497. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43498. })(BABYLON || (BABYLON = {}));
  43499. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43500. "use strict";
  43501. var BABYLON;
  43502. (function (BABYLON) {
  43503. BABYLON.CameraInputTypes = {};
  43504. var CameraInputsManager = /** @class */ (function () {
  43505. function CameraInputsManager(camera) {
  43506. this.attached = {};
  43507. this.camera = camera;
  43508. this.checkInputs = function () { };
  43509. }
  43510. /**
  43511. * Add an input method to a camera.
  43512. * builtin inputs example: camera.inputs.addGamepad();
  43513. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43514. * @param input camera input method
  43515. */
  43516. CameraInputsManager.prototype.add = function (input) {
  43517. var type = input.getSimpleName();
  43518. if (this.attached[type]) {
  43519. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43520. return;
  43521. }
  43522. this.attached[type] = input;
  43523. input.camera = this.camera;
  43524. //for checkInputs, we are dynamically creating a function
  43525. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43526. if (input.checkInputs) {
  43527. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43528. }
  43529. if (this.attachedElement) {
  43530. input.attachControl(this.attachedElement);
  43531. }
  43532. };
  43533. /**
  43534. * Remove a specific input method from a camera
  43535. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43536. * @param inputToRemove camera input method
  43537. */
  43538. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43539. for (var cam in this.attached) {
  43540. var input = this.attached[cam];
  43541. if (input === inputToRemove) {
  43542. input.detachControl(this.attachedElement);
  43543. input.camera = null;
  43544. delete this.attached[cam];
  43545. this.rebuildInputCheck();
  43546. }
  43547. }
  43548. };
  43549. CameraInputsManager.prototype.removeByType = function (inputType) {
  43550. for (var cam in this.attached) {
  43551. var input = this.attached[cam];
  43552. if (input.getClassName() === inputType) {
  43553. input.detachControl(this.attachedElement);
  43554. input.camera = null;
  43555. delete this.attached[cam];
  43556. this.rebuildInputCheck();
  43557. }
  43558. }
  43559. };
  43560. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43561. var current = this.checkInputs;
  43562. return function () {
  43563. current();
  43564. fn();
  43565. };
  43566. };
  43567. CameraInputsManager.prototype.attachInput = function (input) {
  43568. if (this.attachedElement) {
  43569. input.attachControl(this.attachedElement, this.noPreventDefault);
  43570. }
  43571. };
  43572. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43573. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43574. if (this.attachedElement) {
  43575. return;
  43576. }
  43577. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43578. this.attachedElement = element;
  43579. this.noPreventDefault = noPreventDefault;
  43580. for (var cam in this.attached) {
  43581. this.attached[cam].attachControl(element, noPreventDefault);
  43582. }
  43583. };
  43584. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43585. if (disconnect === void 0) { disconnect = false; }
  43586. if (this.attachedElement !== element) {
  43587. return;
  43588. }
  43589. for (var cam in this.attached) {
  43590. this.attached[cam].detachControl(element);
  43591. if (disconnect) {
  43592. this.attached[cam].camera = null;
  43593. }
  43594. }
  43595. this.attachedElement = null;
  43596. };
  43597. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43598. this.checkInputs = function () { };
  43599. for (var cam in this.attached) {
  43600. var input = this.attached[cam];
  43601. if (input.checkInputs) {
  43602. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43603. }
  43604. }
  43605. };
  43606. /**
  43607. * Remove all attached input methods from a camera
  43608. */
  43609. CameraInputsManager.prototype.clear = function () {
  43610. if (this.attachedElement) {
  43611. this.detachElement(this.attachedElement, true);
  43612. }
  43613. this.attached = {};
  43614. this.attachedElement = null;
  43615. this.checkInputs = function () { };
  43616. };
  43617. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43618. var inputs = {};
  43619. for (var cam in this.attached) {
  43620. var input = this.attached[cam];
  43621. var res = BABYLON.SerializationHelper.Serialize(input);
  43622. inputs[input.getClassName()] = res;
  43623. }
  43624. serializedCamera.inputsmgr = inputs;
  43625. };
  43626. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43627. var parsedInputs = parsedCamera.inputsmgr;
  43628. if (parsedInputs) {
  43629. this.clear();
  43630. for (var n in parsedInputs) {
  43631. var construct = BABYLON.CameraInputTypes[n];
  43632. if (construct) {
  43633. var parsedinput = parsedInputs[n];
  43634. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43635. this.add(input);
  43636. }
  43637. }
  43638. }
  43639. else {
  43640. //2016-03-08 this part is for managing backward compatibility
  43641. for (var n in this.attached) {
  43642. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43643. if (construct) {
  43644. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43645. this.remove(this.attached[n]);
  43646. this.add(input);
  43647. }
  43648. }
  43649. }
  43650. };
  43651. return CameraInputsManager;
  43652. }());
  43653. BABYLON.CameraInputsManager = CameraInputsManager;
  43654. })(BABYLON || (BABYLON = {}));
  43655. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43656. "use strict";
  43657. var BABYLON;
  43658. (function (BABYLON) {
  43659. var TargetCamera = /** @class */ (function (_super) {
  43660. __extends(TargetCamera, _super);
  43661. function TargetCamera(name, position, scene) {
  43662. var _this = _super.call(this, name, position, scene) || this;
  43663. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43664. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43665. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43666. _this.speed = 2.0;
  43667. _this.noRotationConstraint = false;
  43668. _this.lockedTarget = null;
  43669. _this._currentTarget = BABYLON.Vector3.Zero();
  43670. _this._viewMatrix = BABYLON.Matrix.Zero();
  43671. _this._camMatrix = BABYLON.Matrix.Zero();
  43672. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43673. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43674. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43675. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43676. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43677. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43678. _this._tempMatrix = BABYLON.Matrix.Zero();
  43679. return _this;
  43680. }
  43681. TargetCamera.prototype.getFrontPosition = function (distance) {
  43682. this.getWorldMatrix();
  43683. var direction = this.getTarget().subtract(this.position);
  43684. direction.normalize();
  43685. direction.scaleInPlace(distance);
  43686. return this.globalPosition.add(direction);
  43687. };
  43688. TargetCamera.prototype._getLockedTargetPosition = function () {
  43689. if (!this.lockedTarget) {
  43690. return null;
  43691. }
  43692. if (this.lockedTarget.absolutePosition) {
  43693. this.lockedTarget.computeWorldMatrix();
  43694. }
  43695. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43696. };
  43697. TargetCamera.prototype.storeState = function () {
  43698. this._storedPosition = this.position.clone();
  43699. this._storedRotation = this.rotation.clone();
  43700. if (this.rotationQuaternion) {
  43701. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43702. }
  43703. return _super.prototype.storeState.call(this);
  43704. };
  43705. /**
  43706. * Restored camera state. You must call storeState() first
  43707. */
  43708. TargetCamera.prototype._restoreStateValues = function () {
  43709. if (!_super.prototype._restoreStateValues.call(this)) {
  43710. return false;
  43711. }
  43712. this.position = this._storedPosition.clone();
  43713. this.rotation = this._storedRotation.clone();
  43714. if (this.rotationQuaternion) {
  43715. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43716. }
  43717. this.cameraDirection.copyFromFloats(0, 0, 0);
  43718. this.cameraRotation.copyFromFloats(0, 0);
  43719. return true;
  43720. };
  43721. // Cache
  43722. TargetCamera.prototype._initCache = function () {
  43723. _super.prototype._initCache.call(this);
  43724. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43725. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43726. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43727. };
  43728. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43729. if (!ignoreParentClass) {
  43730. _super.prototype._updateCache.call(this);
  43731. }
  43732. var lockedTargetPosition = this._getLockedTargetPosition();
  43733. if (!lockedTargetPosition) {
  43734. this._cache.lockedTarget = null;
  43735. }
  43736. else {
  43737. if (!this._cache.lockedTarget) {
  43738. this._cache.lockedTarget = lockedTargetPosition.clone();
  43739. }
  43740. else {
  43741. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43742. }
  43743. }
  43744. this._cache.rotation.copyFrom(this.rotation);
  43745. if (this.rotationQuaternion)
  43746. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43747. };
  43748. // Synchronized
  43749. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43750. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43751. return false;
  43752. }
  43753. var lockedTargetPosition = this._getLockedTargetPosition();
  43754. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43755. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43756. };
  43757. // Methods
  43758. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43759. var engine = this.getEngine();
  43760. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43761. };
  43762. // Target
  43763. TargetCamera.prototype.setTarget = function (target) {
  43764. this.upVector.normalize();
  43765. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43766. this._camMatrix.invert();
  43767. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43768. var vDir = target.subtract(this.position);
  43769. if (vDir.x >= 0.0) {
  43770. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43771. }
  43772. else {
  43773. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43774. }
  43775. this.rotation.z = 0;
  43776. if (isNaN(this.rotation.x)) {
  43777. this.rotation.x = 0;
  43778. }
  43779. if (isNaN(this.rotation.y)) {
  43780. this.rotation.y = 0;
  43781. }
  43782. if (isNaN(this.rotation.z)) {
  43783. this.rotation.z = 0;
  43784. }
  43785. if (this.rotationQuaternion) {
  43786. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43787. }
  43788. };
  43789. /**
  43790. * Return the current target position of the camera. This value is expressed in local space.
  43791. */
  43792. TargetCamera.prototype.getTarget = function () {
  43793. return this._currentTarget;
  43794. };
  43795. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43796. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43797. };
  43798. TargetCamera.prototype._updatePosition = function () {
  43799. if (this.parent) {
  43800. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43801. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43802. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43803. return;
  43804. }
  43805. this.position.addInPlace(this.cameraDirection);
  43806. };
  43807. TargetCamera.prototype._checkInputs = function () {
  43808. var needToMove = this._decideIfNeedsToMove();
  43809. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43810. // Move
  43811. if (needToMove) {
  43812. this._updatePosition();
  43813. }
  43814. // Rotate
  43815. if (needToRotate) {
  43816. this.rotation.x += this.cameraRotation.x;
  43817. this.rotation.y += this.cameraRotation.y;
  43818. //rotate, if quaternion is set and rotation was used
  43819. if (this.rotationQuaternion) {
  43820. var len = this.rotation.lengthSquared();
  43821. if (len) {
  43822. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43823. }
  43824. }
  43825. if (!this.noRotationConstraint) {
  43826. var limit = (Math.PI / 2) * 0.95;
  43827. if (this.rotation.x > limit)
  43828. this.rotation.x = limit;
  43829. if (this.rotation.x < -limit)
  43830. this.rotation.x = -limit;
  43831. }
  43832. }
  43833. // Inertia
  43834. if (needToMove) {
  43835. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43836. this.cameraDirection.x = 0;
  43837. }
  43838. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43839. this.cameraDirection.y = 0;
  43840. }
  43841. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43842. this.cameraDirection.z = 0;
  43843. }
  43844. this.cameraDirection.scaleInPlace(this.inertia);
  43845. }
  43846. if (needToRotate) {
  43847. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43848. this.cameraRotation.x = 0;
  43849. }
  43850. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43851. this.cameraRotation.y = 0;
  43852. }
  43853. this.cameraRotation.scaleInPlace(this.inertia);
  43854. }
  43855. _super.prototype._checkInputs.call(this);
  43856. };
  43857. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43858. if (this.rotationQuaternion) {
  43859. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43860. }
  43861. else {
  43862. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43863. }
  43864. //update the up vector!
  43865. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43866. };
  43867. TargetCamera.prototype._getViewMatrix = function () {
  43868. if (this.lockedTarget) {
  43869. this.setTarget(this._getLockedTargetPosition());
  43870. }
  43871. // Compute
  43872. this._updateCameraRotationMatrix();
  43873. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43874. // Computing target and final matrix
  43875. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43876. if (this.getScene().useRightHandedSystem) {
  43877. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43878. }
  43879. else {
  43880. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43881. }
  43882. return this._viewMatrix;
  43883. };
  43884. /**
  43885. * @override
  43886. * Override Camera.createRigCamera
  43887. */
  43888. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43889. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43890. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43891. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43892. if (!this.rotationQuaternion) {
  43893. this.rotationQuaternion = new BABYLON.Quaternion();
  43894. }
  43895. rigCamera._cameraRigParams = {};
  43896. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43897. }
  43898. return rigCamera;
  43899. }
  43900. return null;
  43901. };
  43902. /**
  43903. * @override
  43904. * Override Camera._updateRigCameras
  43905. */
  43906. TargetCamera.prototype._updateRigCameras = function () {
  43907. var camLeft = this._rigCameras[0];
  43908. var camRight = this._rigCameras[1];
  43909. switch (this.cameraRigMode) {
  43910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43912. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43914. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43915. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43916. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43917. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43918. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43919. camLeft.setTarget(this.getTarget());
  43920. camRight.setTarget(this.getTarget());
  43921. break;
  43922. case BABYLON.Camera.RIG_MODE_VR:
  43923. if (camLeft.rotationQuaternion) {
  43924. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43925. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43926. }
  43927. else {
  43928. camLeft.rotation.copyFrom(this.rotation);
  43929. camRight.rotation.copyFrom(this.rotation);
  43930. }
  43931. camLeft.position.copyFrom(this.position);
  43932. camRight.position.copyFrom(this.position);
  43933. break;
  43934. }
  43935. _super.prototype._updateRigCameras.call(this);
  43936. };
  43937. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43938. if (!this._rigCamTransformMatrix) {
  43939. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43940. }
  43941. var target = this.getTarget();
  43942. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43943. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43944. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43945. };
  43946. TargetCamera.prototype.getClassName = function () {
  43947. return "TargetCamera";
  43948. };
  43949. __decorate([
  43950. BABYLON.serializeAsVector3()
  43951. ], TargetCamera.prototype, "rotation", void 0);
  43952. __decorate([
  43953. BABYLON.serialize()
  43954. ], TargetCamera.prototype, "speed", void 0);
  43955. __decorate([
  43956. BABYLON.serializeAsMeshReference("lockedTargetId")
  43957. ], TargetCamera.prototype, "lockedTarget", void 0);
  43958. return TargetCamera;
  43959. }(BABYLON.Camera));
  43960. BABYLON.TargetCamera = TargetCamera;
  43961. })(BABYLON || (BABYLON = {}));
  43962. //# sourceMappingURL=babylon.targetCamera.js.map
  43963. "use strict";
  43964. var BABYLON;
  43965. (function (BABYLON) {
  43966. var FreeCameraMouseInput = /** @class */ (function () {
  43967. function FreeCameraMouseInput(touchEnabled) {
  43968. if (touchEnabled === void 0) { touchEnabled = true; }
  43969. this.touchEnabled = touchEnabled;
  43970. this.buttons = [0, 1, 2];
  43971. this.angularSensibility = 2000.0;
  43972. this.previousPosition = null;
  43973. }
  43974. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43975. var _this = this;
  43976. var engine = this.camera.getEngine();
  43977. if (!this._pointerInput) {
  43978. this._pointerInput = function (p, s) {
  43979. var evt = p.event;
  43980. if (engine.isInVRExclusivePointerMode) {
  43981. return;
  43982. }
  43983. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43984. return;
  43985. }
  43986. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43987. return;
  43988. }
  43989. var srcElement = (evt.srcElement || evt.target);
  43990. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43991. try {
  43992. srcElement.setPointerCapture(evt.pointerId);
  43993. }
  43994. catch (e) {
  43995. //Nothing to do with the error. Execution will continue.
  43996. }
  43997. _this.previousPosition = {
  43998. x: evt.clientX,
  43999. y: evt.clientY
  44000. };
  44001. if (!noPreventDefault) {
  44002. evt.preventDefault();
  44003. element.focus();
  44004. }
  44005. }
  44006. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44007. try {
  44008. srcElement.releasePointerCapture(evt.pointerId);
  44009. }
  44010. catch (e) {
  44011. //Nothing to do with the error.
  44012. }
  44013. _this.previousPosition = null;
  44014. if (!noPreventDefault) {
  44015. evt.preventDefault();
  44016. }
  44017. }
  44018. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44019. if (!_this.previousPosition || engine.isPointerLock) {
  44020. return;
  44021. }
  44022. var offsetX = evt.clientX - _this.previousPosition.x;
  44023. var offsetY = evt.clientY - _this.previousPosition.y;
  44024. if (_this.camera.getScene().useRightHandedSystem) {
  44025. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44026. }
  44027. else {
  44028. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44029. }
  44030. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44031. _this.previousPosition = {
  44032. x: evt.clientX,
  44033. y: evt.clientY
  44034. };
  44035. if (!noPreventDefault) {
  44036. evt.preventDefault();
  44037. }
  44038. }
  44039. };
  44040. }
  44041. this._onMouseMove = function (evt) {
  44042. if (!engine.isPointerLock) {
  44043. return;
  44044. }
  44045. if (engine.isInVRExclusivePointerMode) {
  44046. return;
  44047. }
  44048. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44049. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44050. if (_this.camera.getScene().useRightHandedSystem) {
  44051. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44052. }
  44053. else {
  44054. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44055. }
  44056. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44057. _this.previousPosition = null;
  44058. if (!noPreventDefault) {
  44059. evt.preventDefault();
  44060. }
  44061. };
  44062. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44063. element.addEventListener("mousemove", this._onMouseMove, false);
  44064. };
  44065. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44066. if (this._observer && element) {
  44067. this.camera.getScene().onPointerObservable.remove(this._observer);
  44068. if (this._onMouseMove) {
  44069. element.removeEventListener("mousemove", this._onMouseMove);
  44070. }
  44071. this._observer = null;
  44072. this._onMouseMove = null;
  44073. this.previousPosition = null;
  44074. }
  44075. };
  44076. FreeCameraMouseInput.prototype.getClassName = function () {
  44077. return "FreeCameraMouseInput";
  44078. };
  44079. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44080. return "mouse";
  44081. };
  44082. __decorate([
  44083. BABYLON.serialize()
  44084. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44085. __decorate([
  44086. BABYLON.serialize()
  44087. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44088. return FreeCameraMouseInput;
  44089. }());
  44090. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44091. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44092. })(BABYLON || (BABYLON = {}));
  44093. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44094. "use strict";
  44095. var BABYLON;
  44096. (function (BABYLON) {
  44097. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44098. function FreeCameraKeyboardMoveInput() {
  44099. this._keys = new Array();
  44100. this.keysUp = [38];
  44101. this.keysDown = [40];
  44102. this.keysLeft = [37];
  44103. this.keysRight = [39];
  44104. }
  44105. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44106. var _this = this;
  44107. if (this._onCanvasBlurObserver) {
  44108. return;
  44109. }
  44110. this._scene = this.camera.getScene();
  44111. this._engine = this._scene.getEngine();
  44112. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44113. _this._keys = [];
  44114. });
  44115. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44116. var evt = info.event;
  44117. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44118. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44119. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44120. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44121. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44122. var index = _this._keys.indexOf(evt.keyCode);
  44123. if (index === -1) {
  44124. _this._keys.push(evt.keyCode);
  44125. }
  44126. if (!noPreventDefault) {
  44127. evt.preventDefault();
  44128. }
  44129. }
  44130. }
  44131. else {
  44132. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44133. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44134. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44135. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44136. var index = _this._keys.indexOf(evt.keyCode);
  44137. if (index >= 0) {
  44138. _this._keys.splice(index, 1);
  44139. }
  44140. if (!noPreventDefault) {
  44141. evt.preventDefault();
  44142. }
  44143. }
  44144. }
  44145. });
  44146. };
  44147. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44148. if (this._scene) {
  44149. if (this._onKeyboardObserver) {
  44150. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44151. }
  44152. if (this._onCanvasBlurObserver) {
  44153. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44154. }
  44155. this._onKeyboardObserver = null;
  44156. this._onCanvasBlurObserver = null;
  44157. }
  44158. this._keys = [];
  44159. };
  44160. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44161. if (this._onKeyboardObserver) {
  44162. var camera = this.camera;
  44163. // Keyboard
  44164. for (var index = 0; index < this._keys.length; index++) {
  44165. var keyCode = this._keys[index];
  44166. var speed = camera._computeLocalCameraSpeed();
  44167. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44168. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44169. }
  44170. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44171. camera._localDirection.copyFromFloats(0, 0, speed);
  44172. }
  44173. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44174. camera._localDirection.copyFromFloats(speed, 0, 0);
  44175. }
  44176. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44177. camera._localDirection.copyFromFloats(0, 0, -speed);
  44178. }
  44179. if (camera.getScene().useRightHandedSystem) {
  44180. camera._localDirection.z *= -1;
  44181. }
  44182. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44183. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44184. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44185. }
  44186. }
  44187. };
  44188. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44189. return "FreeCameraKeyboardMoveInput";
  44190. };
  44191. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44192. this._keys = [];
  44193. };
  44194. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44195. return "keyboard";
  44196. };
  44197. __decorate([
  44198. BABYLON.serialize()
  44199. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44200. __decorate([
  44201. BABYLON.serialize()
  44202. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44203. __decorate([
  44204. BABYLON.serialize()
  44205. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44206. __decorate([
  44207. BABYLON.serialize()
  44208. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44209. return FreeCameraKeyboardMoveInput;
  44210. }());
  44211. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44212. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44213. })(BABYLON || (BABYLON = {}));
  44214. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44215. "use strict";
  44216. var BABYLON;
  44217. (function (BABYLON) {
  44218. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44219. __extends(FreeCameraInputsManager, _super);
  44220. function FreeCameraInputsManager(camera) {
  44221. return _super.call(this, camera) || this;
  44222. }
  44223. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44224. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44225. return this;
  44226. };
  44227. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44228. if (touchEnabled === void 0) { touchEnabled = true; }
  44229. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44230. return this;
  44231. };
  44232. FreeCameraInputsManager.prototype.addGamepad = function () {
  44233. this.add(new BABYLON.FreeCameraGamepadInput());
  44234. return this;
  44235. };
  44236. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44237. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44238. return this;
  44239. };
  44240. FreeCameraInputsManager.prototype.addTouch = function () {
  44241. this.add(new BABYLON.FreeCameraTouchInput());
  44242. return this;
  44243. };
  44244. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44245. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44246. return this;
  44247. };
  44248. return FreeCameraInputsManager;
  44249. }(BABYLON.CameraInputsManager));
  44250. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44251. })(BABYLON || (BABYLON = {}));
  44252. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44253. "use strict";
  44254. var BABYLON;
  44255. (function (BABYLON) {
  44256. var FreeCamera = /** @class */ (function (_super) {
  44257. __extends(FreeCamera, _super);
  44258. function FreeCamera(name, position, scene) {
  44259. var _this = _super.call(this, name, position, scene) || this;
  44260. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44261. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44262. _this.checkCollisions = false;
  44263. _this.applyGravity = false;
  44264. _this._needMoveForGravity = false;
  44265. _this._oldPosition = BABYLON.Vector3.Zero();
  44266. _this._diffPosition = BABYLON.Vector3.Zero();
  44267. _this._newPosition = BABYLON.Vector3.Zero();
  44268. // Collisions
  44269. _this._collisionMask = -1;
  44270. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44271. if (collidedMesh === void 0) { collidedMesh = null; }
  44272. //TODO move this to the collision coordinator!
  44273. if (_this.getScene().workerCollisions)
  44274. newPosition.multiplyInPlace(_this._collider._radius);
  44275. var updatePosition = function (newPos) {
  44276. _this._newPosition.copyFrom(newPos);
  44277. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44278. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44279. _this.position.addInPlace(_this._diffPosition);
  44280. if (_this.onCollide && collidedMesh) {
  44281. _this.onCollide(collidedMesh);
  44282. }
  44283. }
  44284. };
  44285. updatePosition(newPosition);
  44286. };
  44287. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44288. _this.inputs.addKeyboard().addMouse();
  44289. return _this;
  44290. }
  44291. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44292. //-- begin properties for backward compatibility for inputs
  44293. /**
  44294. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44295. * Higher values reduce sensitivity.
  44296. */
  44297. get: function () {
  44298. var mouse = this.inputs.attached["mouse"];
  44299. if (mouse)
  44300. return mouse.angularSensibility;
  44301. return 0;
  44302. },
  44303. /**
  44304. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44305. * Higher values reduce sensitivity.
  44306. */
  44307. set: function (value) {
  44308. var mouse = this.inputs.attached["mouse"];
  44309. if (mouse)
  44310. mouse.angularSensibility = value;
  44311. },
  44312. enumerable: true,
  44313. configurable: true
  44314. });
  44315. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44316. get: function () {
  44317. var keyboard = this.inputs.attached["keyboard"];
  44318. if (keyboard)
  44319. return keyboard.keysUp;
  44320. return [];
  44321. },
  44322. set: function (value) {
  44323. var keyboard = this.inputs.attached["keyboard"];
  44324. if (keyboard)
  44325. keyboard.keysUp = value;
  44326. },
  44327. enumerable: true,
  44328. configurable: true
  44329. });
  44330. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44331. get: function () {
  44332. var keyboard = this.inputs.attached["keyboard"];
  44333. if (keyboard)
  44334. return keyboard.keysDown;
  44335. return [];
  44336. },
  44337. set: function (value) {
  44338. var keyboard = this.inputs.attached["keyboard"];
  44339. if (keyboard)
  44340. keyboard.keysDown = value;
  44341. },
  44342. enumerable: true,
  44343. configurable: true
  44344. });
  44345. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44346. get: function () {
  44347. var keyboard = this.inputs.attached["keyboard"];
  44348. if (keyboard)
  44349. return keyboard.keysLeft;
  44350. return [];
  44351. },
  44352. set: function (value) {
  44353. var keyboard = this.inputs.attached["keyboard"];
  44354. if (keyboard)
  44355. keyboard.keysLeft = value;
  44356. },
  44357. enumerable: true,
  44358. configurable: true
  44359. });
  44360. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44361. get: function () {
  44362. var keyboard = this.inputs.attached["keyboard"];
  44363. if (keyboard)
  44364. return keyboard.keysRight;
  44365. return [];
  44366. },
  44367. set: function (value) {
  44368. var keyboard = this.inputs.attached["keyboard"];
  44369. if (keyboard)
  44370. keyboard.keysRight = value;
  44371. },
  44372. enumerable: true,
  44373. configurable: true
  44374. });
  44375. // Controls
  44376. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44377. this.inputs.attachElement(element, noPreventDefault);
  44378. };
  44379. FreeCamera.prototype.detachControl = function (element) {
  44380. this.inputs.detachElement(element);
  44381. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44382. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44383. };
  44384. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44385. get: function () {
  44386. return this._collisionMask;
  44387. },
  44388. set: function (mask) {
  44389. this._collisionMask = !isNaN(mask) ? mask : -1;
  44390. },
  44391. enumerable: true,
  44392. configurable: true
  44393. });
  44394. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44395. var globalPosition;
  44396. if (this.parent) {
  44397. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44398. }
  44399. else {
  44400. globalPosition = this.position;
  44401. }
  44402. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44403. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44404. if (!this._collider) {
  44405. this._collider = new BABYLON.Collider();
  44406. }
  44407. this._collider._radius = this.ellipsoid;
  44408. this._collider.collisionMask = this._collisionMask;
  44409. //no need for clone, as long as gravity is not on.
  44410. var actualDisplacement = displacement;
  44411. //add gravity to the direction to prevent the dual-collision checking
  44412. if (this.applyGravity) {
  44413. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44414. actualDisplacement = displacement.add(this.getScene().gravity);
  44415. }
  44416. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44417. };
  44418. FreeCamera.prototype._checkInputs = function () {
  44419. if (!this._localDirection) {
  44420. this._localDirection = BABYLON.Vector3.Zero();
  44421. this._transformedDirection = BABYLON.Vector3.Zero();
  44422. }
  44423. this.inputs.checkInputs();
  44424. _super.prototype._checkInputs.call(this);
  44425. };
  44426. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44427. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44428. };
  44429. FreeCamera.prototype._updatePosition = function () {
  44430. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44431. this._collideWithWorld(this.cameraDirection);
  44432. }
  44433. else {
  44434. _super.prototype._updatePosition.call(this);
  44435. }
  44436. };
  44437. FreeCamera.prototype.dispose = function () {
  44438. this.inputs.clear();
  44439. _super.prototype.dispose.call(this);
  44440. };
  44441. FreeCamera.prototype.getClassName = function () {
  44442. return "FreeCamera";
  44443. };
  44444. __decorate([
  44445. BABYLON.serializeAsVector3()
  44446. ], FreeCamera.prototype, "ellipsoid", void 0);
  44447. __decorate([
  44448. BABYLON.serializeAsVector3()
  44449. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44450. __decorate([
  44451. BABYLON.serialize()
  44452. ], FreeCamera.prototype, "checkCollisions", void 0);
  44453. __decorate([
  44454. BABYLON.serialize()
  44455. ], FreeCamera.prototype, "applyGravity", void 0);
  44456. return FreeCamera;
  44457. }(BABYLON.TargetCamera));
  44458. BABYLON.FreeCamera = FreeCamera;
  44459. })(BABYLON || (BABYLON = {}));
  44460. //# sourceMappingURL=babylon.freeCamera.js.map
  44461. "use strict";
  44462. var BABYLON;
  44463. (function (BABYLON) {
  44464. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44465. function ArcRotateCameraKeyboardMoveInput() {
  44466. this._keys = new Array();
  44467. this.keysUp = [38];
  44468. this.keysDown = [40];
  44469. this.keysLeft = [37];
  44470. this.keysRight = [39];
  44471. this.keysReset = [220];
  44472. this.panningSensibility = 50.0;
  44473. this.zoomingSensibility = 25.0;
  44474. this.useAltToZoom = true;
  44475. }
  44476. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44477. var _this = this;
  44478. if (this._onCanvasBlurObserver) {
  44479. return;
  44480. }
  44481. this._scene = this.camera.getScene();
  44482. this._engine = this._scene.getEngine();
  44483. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44484. _this._keys = [];
  44485. });
  44486. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44487. var evt = info.event;
  44488. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44489. _this._ctrlPressed = evt.ctrlKey;
  44490. _this._altPressed = evt.altKey;
  44491. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44492. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44493. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44494. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44495. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44496. var index = _this._keys.indexOf(evt.keyCode);
  44497. if (index === -1) {
  44498. _this._keys.push(evt.keyCode);
  44499. }
  44500. if (evt.preventDefault) {
  44501. if (!noPreventDefault) {
  44502. evt.preventDefault();
  44503. }
  44504. }
  44505. }
  44506. }
  44507. else {
  44508. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44509. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44510. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44511. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44512. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44513. var index = _this._keys.indexOf(evt.keyCode);
  44514. if (index >= 0) {
  44515. _this._keys.splice(index, 1);
  44516. }
  44517. if (evt.preventDefault) {
  44518. if (!noPreventDefault) {
  44519. evt.preventDefault();
  44520. }
  44521. }
  44522. }
  44523. }
  44524. });
  44525. };
  44526. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44527. if (this._scene) {
  44528. if (this._onKeyboardObserver) {
  44529. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44530. }
  44531. if (this._onCanvasBlurObserver) {
  44532. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44533. }
  44534. this._onKeyboardObserver = null;
  44535. this._onCanvasBlurObserver = null;
  44536. }
  44537. this._keys = [];
  44538. };
  44539. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44540. if (this._onKeyboardObserver) {
  44541. var camera = this.camera;
  44542. for (var index = 0; index < this._keys.length; index++) {
  44543. var keyCode = this._keys[index];
  44544. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44545. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44546. camera.inertialPanningX -= 1 / this.panningSensibility;
  44547. }
  44548. else {
  44549. camera.inertialAlphaOffset -= 0.01;
  44550. }
  44551. }
  44552. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44553. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44554. camera.inertialPanningY += 1 / this.panningSensibility;
  44555. }
  44556. else if (this._altPressed && this.useAltToZoom) {
  44557. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44558. }
  44559. else {
  44560. camera.inertialBetaOffset -= 0.01;
  44561. }
  44562. }
  44563. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44564. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44565. camera.inertialPanningX += 1 / this.panningSensibility;
  44566. }
  44567. else {
  44568. camera.inertialAlphaOffset += 0.01;
  44569. }
  44570. }
  44571. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44572. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44573. camera.inertialPanningY -= 1 / this.panningSensibility;
  44574. }
  44575. else if (this._altPressed && this.useAltToZoom) {
  44576. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44577. }
  44578. else {
  44579. camera.inertialBetaOffset += 0.01;
  44580. }
  44581. }
  44582. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44583. camera.restoreState();
  44584. }
  44585. }
  44586. }
  44587. };
  44588. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44589. return "ArcRotateCameraKeyboardMoveInput";
  44590. };
  44591. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44592. return "keyboard";
  44593. };
  44594. __decorate([
  44595. BABYLON.serialize()
  44596. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44597. __decorate([
  44598. BABYLON.serialize()
  44599. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44600. __decorate([
  44601. BABYLON.serialize()
  44602. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44603. __decorate([
  44604. BABYLON.serialize()
  44605. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44612. __decorate([
  44613. BABYLON.serialize()
  44614. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44618. return ArcRotateCameraKeyboardMoveInput;
  44619. }());
  44620. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44621. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44622. })(BABYLON || (BABYLON = {}));
  44623. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44624. "use strict";
  44625. var BABYLON;
  44626. (function (BABYLON) {
  44627. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44628. function ArcRotateCameraMouseWheelInput() {
  44629. this.wheelPrecision = 3.0;
  44630. /**
  44631. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44632. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44633. */
  44634. this.wheelDeltaPercentage = 0;
  44635. }
  44636. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44637. var _this = this;
  44638. this._wheel = function (p, s) {
  44639. //sanity check - this should be a PointerWheel event.
  44640. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44641. return;
  44642. var event = p.event;
  44643. var delta = 0;
  44644. if (event.wheelDelta) {
  44645. if (_this.wheelDeltaPercentage) {
  44646. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44647. if (event.wheelDelta > 0) {
  44648. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44649. }
  44650. else {
  44651. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44652. }
  44653. }
  44654. else {
  44655. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44656. }
  44657. }
  44658. else if (event.detail) {
  44659. delta = -event.detail / _this.wheelPrecision;
  44660. }
  44661. if (delta)
  44662. _this.camera.inertialRadiusOffset += delta;
  44663. if (event.preventDefault) {
  44664. if (!noPreventDefault) {
  44665. event.preventDefault();
  44666. }
  44667. }
  44668. };
  44669. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44670. };
  44671. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44672. if (this._observer && element) {
  44673. this.camera.getScene().onPointerObservable.remove(this._observer);
  44674. this._observer = null;
  44675. this._wheel = null;
  44676. }
  44677. };
  44678. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44679. return "ArcRotateCameraMouseWheelInput";
  44680. };
  44681. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44682. return "mousewheel";
  44683. };
  44684. __decorate([
  44685. BABYLON.serialize()
  44686. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44687. __decorate([
  44688. BABYLON.serialize()
  44689. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44690. return ArcRotateCameraMouseWheelInput;
  44691. }());
  44692. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44693. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44694. })(BABYLON || (BABYLON = {}));
  44695. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44696. "use strict";
  44697. var BABYLON;
  44698. (function (BABYLON) {
  44699. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44700. function ArcRotateCameraPointersInput() {
  44701. this.buttons = [0, 1, 2];
  44702. this.angularSensibilityX = 1000.0;
  44703. this.angularSensibilityY = 1000.0;
  44704. this.pinchPrecision = 12.0;
  44705. /**
  44706. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44707. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44708. */
  44709. this.pinchDeltaPercentage = 0;
  44710. this.panningSensibility = 1000.0;
  44711. this.multiTouchPanning = true;
  44712. this.multiTouchPanAndZoom = true;
  44713. this._isPanClick = false;
  44714. this.pinchInwards = true;
  44715. }
  44716. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44717. var _this = this;
  44718. var engine = this.camera.getEngine();
  44719. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44720. var pointA = null;
  44721. var pointB = null;
  44722. var previousPinchSquaredDistance = 0;
  44723. var initialDistance = 0;
  44724. var twoFingerActivityCount = 0;
  44725. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44726. this._pointerInput = function (p, s) {
  44727. var evt = p.event;
  44728. var isTouch = p.event.pointerType === "touch";
  44729. if (engine.isInVRExclusivePointerMode) {
  44730. return;
  44731. }
  44732. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44733. return;
  44734. }
  44735. var srcElement = (evt.srcElement || evt.target);
  44736. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44737. try {
  44738. srcElement.setPointerCapture(evt.pointerId);
  44739. }
  44740. catch (e) {
  44741. //Nothing to do with the error. Execution will continue.
  44742. }
  44743. // Manage panning with pan button click
  44744. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44745. // manage pointers
  44746. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44747. if (pointA === null) {
  44748. pointA = cacheSoloPointer;
  44749. }
  44750. else if (pointB === null) {
  44751. pointB = cacheSoloPointer;
  44752. }
  44753. if (!noPreventDefault) {
  44754. evt.preventDefault();
  44755. element.focus();
  44756. }
  44757. }
  44758. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44759. _this.camera.restoreState();
  44760. }
  44761. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44762. try {
  44763. srcElement.releasePointerCapture(evt.pointerId);
  44764. }
  44765. catch (e) {
  44766. //Nothing to do with the error.
  44767. }
  44768. cacheSoloPointer = null;
  44769. previousPinchSquaredDistance = 0;
  44770. previousMultiTouchPanPosition.isPaning = false;
  44771. previousMultiTouchPanPosition.isPinching = false;
  44772. twoFingerActivityCount = 0;
  44773. initialDistance = 0;
  44774. if (!isTouch) {
  44775. pointB = null; // Mouse and pen are mono pointer
  44776. }
  44777. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44778. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44779. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44780. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44781. if (engine.badOS) {
  44782. pointA = pointB = null;
  44783. }
  44784. else {
  44785. //only remove the impacted pointer in case of multitouch allowing on most
  44786. //platforms switching from rotate to zoom and pan seamlessly.
  44787. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44788. pointA = pointB;
  44789. pointB = null;
  44790. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44791. }
  44792. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44793. pointB = null;
  44794. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44795. }
  44796. else {
  44797. pointA = pointB = null;
  44798. }
  44799. }
  44800. if (!noPreventDefault) {
  44801. evt.preventDefault();
  44802. }
  44803. }
  44804. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44805. if (!noPreventDefault) {
  44806. evt.preventDefault();
  44807. }
  44808. // One button down
  44809. if (pointA && pointB === null && cacheSoloPointer) {
  44810. if (_this.panningSensibility !== 0 &&
  44811. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44812. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44813. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44814. }
  44815. else {
  44816. var offsetX = evt.clientX - cacheSoloPointer.x;
  44817. var offsetY = evt.clientY - cacheSoloPointer.y;
  44818. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44819. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44820. }
  44821. cacheSoloPointer.x = evt.clientX;
  44822. cacheSoloPointer.y = evt.clientY;
  44823. }
  44824. else if (pointA && pointB) {
  44825. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44826. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44827. ed.x = evt.clientX;
  44828. ed.y = evt.clientY;
  44829. var direction = _this.pinchInwards ? 1 : -1;
  44830. var distX = pointA.x - pointB.x;
  44831. var distY = pointA.y - pointB.y;
  44832. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44833. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44834. if (previousPinchSquaredDistance === 0) {
  44835. initialDistance = pinchDistance;
  44836. previousPinchSquaredDistance = pinchSquaredDistance;
  44837. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44838. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44839. return;
  44840. }
  44841. if (_this.multiTouchPanAndZoom) {
  44842. if (_this.pinchDeltaPercentage) {
  44843. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44844. }
  44845. else {
  44846. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44847. (_this.pinchPrecision *
  44848. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44849. direction);
  44850. }
  44851. if (_this.panningSensibility !== 0) {
  44852. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44853. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44854. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44855. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44856. previousMultiTouchPanPosition.x = pointersCenterX;
  44857. previousMultiTouchPanPosition.y = pointersCenterY;
  44858. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44859. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44860. }
  44861. }
  44862. else {
  44863. twoFingerActivityCount++;
  44864. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44865. if (_this.pinchDeltaPercentage) {
  44866. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44867. }
  44868. else {
  44869. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44870. (_this.pinchPrecision *
  44871. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44872. direction);
  44873. }
  44874. previousMultiTouchPanPosition.isPaning = false;
  44875. previousMultiTouchPanPosition.isPinching = true;
  44876. }
  44877. else {
  44878. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44879. if (!previousMultiTouchPanPosition.isPaning) {
  44880. previousMultiTouchPanPosition.isPaning = true;
  44881. previousMultiTouchPanPosition.isPinching = false;
  44882. previousMultiTouchPanPosition.x = ed.x;
  44883. previousMultiTouchPanPosition.y = ed.y;
  44884. return;
  44885. }
  44886. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44887. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44888. }
  44889. }
  44890. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44891. previousMultiTouchPanPosition.x = ed.x;
  44892. previousMultiTouchPanPosition.y = ed.y;
  44893. }
  44894. }
  44895. previousPinchSquaredDistance = pinchSquaredDistance;
  44896. }
  44897. }
  44898. };
  44899. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44900. this._onContextMenu = function (evt) {
  44901. evt.preventDefault();
  44902. };
  44903. if (!this.camera._useCtrlForPanning) {
  44904. element.addEventListener("contextmenu", this._onContextMenu, false);
  44905. }
  44906. this._onLostFocus = function () {
  44907. //this._keys = [];
  44908. pointA = pointB = null;
  44909. previousPinchSquaredDistance = 0;
  44910. previousMultiTouchPanPosition.isPaning = false;
  44911. previousMultiTouchPanPosition.isPinching = false;
  44912. twoFingerActivityCount = 0;
  44913. cacheSoloPointer = null;
  44914. initialDistance = 0;
  44915. };
  44916. this._onMouseMove = function (evt) {
  44917. if (!engine.isPointerLock) {
  44918. return;
  44919. }
  44920. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44921. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44922. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44923. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44924. if (!noPreventDefault) {
  44925. evt.preventDefault();
  44926. }
  44927. };
  44928. this._onGestureStart = function (e) {
  44929. if (window.MSGesture === undefined) {
  44930. return;
  44931. }
  44932. if (!_this._MSGestureHandler) {
  44933. _this._MSGestureHandler = new MSGesture();
  44934. _this._MSGestureHandler.target = element;
  44935. }
  44936. _this._MSGestureHandler.addPointer(e.pointerId);
  44937. };
  44938. this._onGesture = function (e) {
  44939. _this.camera.radius *= e.scale;
  44940. if (e.preventDefault) {
  44941. if (!noPreventDefault) {
  44942. e.stopPropagation();
  44943. e.preventDefault();
  44944. }
  44945. }
  44946. };
  44947. element.addEventListener("mousemove", this._onMouseMove, false);
  44948. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44949. element.addEventListener("MSGestureChange", this._onGesture, false);
  44950. BABYLON.Tools.RegisterTopRootEvents([
  44951. { name: "blur", handler: this._onLostFocus }
  44952. ]);
  44953. };
  44954. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44955. if (this._onLostFocus) {
  44956. BABYLON.Tools.UnregisterTopRootEvents([
  44957. { name: "blur", handler: this._onLostFocus }
  44958. ]);
  44959. }
  44960. if (element && this._observer) {
  44961. this.camera.getScene().onPointerObservable.remove(this._observer);
  44962. this._observer = null;
  44963. if (this._onContextMenu) {
  44964. element.removeEventListener("contextmenu", this._onContextMenu);
  44965. }
  44966. if (this._onMouseMove) {
  44967. element.removeEventListener("mousemove", this._onMouseMove);
  44968. }
  44969. if (this._onGestureStart) {
  44970. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44971. }
  44972. if (this._onGesture) {
  44973. element.removeEventListener("MSGestureChange", this._onGesture);
  44974. }
  44975. this._isPanClick = false;
  44976. this.pinchInwards = true;
  44977. this._onMouseMove = null;
  44978. this._onGestureStart = null;
  44979. this._onGesture = null;
  44980. this._MSGestureHandler = null;
  44981. this._onLostFocus = null;
  44982. this._onContextMenu = null;
  44983. }
  44984. };
  44985. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44986. return "ArcRotateCameraPointersInput";
  44987. };
  44988. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44989. return "pointers";
  44990. };
  44991. __decorate([
  44992. BABYLON.serialize()
  44993. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44994. __decorate([
  44995. BABYLON.serialize()
  44996. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44997. __decorate([
  44998. BABYLON.serialize()
  44999. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  45000. __decorate([
  45001. BABYLON.serialize()
  45002. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  45003. __decorate([
  45004. BABYLON.serialize()
  45005. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  45006. __decorate([
  45007. BABYLON.serialize()
  45008. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45009. __decorate([
  45010. BABYLON.serialize()
  45011. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45012. __decorate([
  45013. BABYLON.serialize()
  45014. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45015. return ArcRotateCameraPointersInput;
  45016. }());
  45017. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45018. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45019. })(BABYLON || (BABYLON = {}));
  45020. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45021. "use strict";
  45022. var BABYLON;
  45023. (function (BABYLON) {
  45024. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45025. __extends(ArcRotateCameraInputsManager, _super);
  45026. function ArcRotateCameraInputsManager(camera) {
  45027. return _super.call(this, camera) || this;
  45028. }
  45029. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45030. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45031. return this;
  45032. };
  45033. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45034. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45035. return this;
  45036. };
  45037. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45038. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45039. return this;
  45040. };
  45041. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45042. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45043. return this;
  45044. };
  45045. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45046. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45047. return this;
  45048. };
  45049. return ArcRotateCameraInputsManager;
  45050. }(BABYLON.CameraInputsManager));
  45051. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45052. })(BABYLON || (BABYLON = {}));
  45053. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45054. "use strict";
  45055. var BABYLON;
  45056. (function (BABYLON) {
  45057. var ArcRotateCamera = /** @class */ (function (_super) {
  45058. __extends(ArcRotateCamera, _super);
  45059. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45060. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45061. _this.inertialAlphaOffset = 0;
  45062. _this.inertialBetaOffset = 0;
  45063. _this.inertialRadiusOffset = 0;
  45064. _this.lowerAlphaLimit = null;
  45065. _this.upperAlphaLimit = null;
  45066. _this.lowerBetaLimit = 0.01;
  45067. _this.upperBetaLimit = Math.PI;
  45068. _this.lowerRadiusLimit = null;
  45069. _this.upperRadiusLimit = null;
  45070. _this.inertialPanningX = 0;
  45071. _this.inertialPanningY = 0;
  45072. _this.pinchToPanMaxDistance = 20;
  45073. _this.panningDistanceLimit = null;
  45074. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45075. _this.panningInertia = 0.9;
  45076. //-- end properties for backward compatibility for inputs
  45077. _this.zoomOnFactor = 1;
  45078. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45079. _this.allowUpsideDown = true;
  45080. _this._viewMatrix = new BABYLON.Matrix();
  45081. // Panning
  45082. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45083. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45084. _this.checkCollisions = false;
  45085. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45086. _this._previousPosition = BABYLON.Vector3.Zero();
  45087. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45088. _this._newPosition = BABYLON.Vector3.Zero();
  45089. _this._computationVector = BABYLON.Vector3.Zero();
  45090. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45091. if (collidedMesh === void 0) { collidedMesh = null; }
  45092. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45093. newPosition.multiplyInPlace(_this._collider._radius);
  45094. }
  45095. if (!collidedMesh) {
  45096. _this._previousPosition.copyFrom(_this.position);
  45097. }
  45098. else {
  45099. _this.setPosition(newPosition);
  45100. if (_this.onCollide) {
  45101. _this.onCollide(collidedMesh);
  45102. }
  45103. }
  45104. // Recompute because of constraints
  45105. var cosa = Math.cos(_this.alpha);
  45106. var sina = Math.sin(_this.alpha);
  45107. var cosb = Math.cos(_this.beta);
  45108. var sinb = Math.sin(_this.beta);
  45109. if (sinb === 0) {
  45110. sinb = 0.0001;
  45111. }
  45112. var target = _this._getTargetPosition();
  45113. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45114. target.addToRef(_this._computationVector, _this._newPosition);
  45115. _this.position.copyFrom(_this._newPosition);
  45116. var up = _this.upVector;
  45117. if (_this.allowUpsideDown && _this.beta < 0) {
  45118. up = up.clone();
  45119. up = up.negate();
  45120. }
  45121. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45122. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45123. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45124. _this._collisionTriggered = false;
  45125. };
  45126. _this._target = BABYLON.Vector3.Zero();
  45127. if (target) {
  45128. _this.setTarget(target);
  45129. }
  45130. _this.alpha = alpha;
  45131. _this.beta = beta;
  45132. _this.radius = radius;
  45133. _this.getViewMatrix();
  45134. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45135. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45136. return _this;
  45137. }
  45138. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45139. get: function () {
  45140. return this._target;
  45141. },
  45142. set: function (value) {
  45143. this.setTarget(value);
  45144. },
  45145. enumerable: true,
  45146. configurable: true
  45147. });
  45148. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45149. //-- begin properties for backward compatibility for inputs
  45150. get: function () {
  45151. var pointers = this.inputs.attached["pointers"];
  45152. if (pointers)
  45153. return pointers.angularSensibilityX;
  45154. return 0;
  45155. },
  45156. set: function (value) {
  45157. var pointers = this.inputs.attached["pointers"];
  45158. if (pointers) {
  45159. pointers.angularSensibilityX = value;
  45160. }
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45166. get: function () {
  45167. var pointers = this.inputs.attached["pointers"];
  45168. if (pointers)
  45169. return pointers.angularSensibilityY;
  45170. return 0;
  45171. },
  45172. set: function (value) {
  45173. var pointers = this.inputs.attached["pointers"];
  45174. if (pointers) {
  45175. pointers.angularSensibilityY = value;
  45176. }
  45177. },
  45178. enumerable: true,
  45179. configurable: true
  45180. });
  45181. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45182. get: function () {
  45183. var pointers = this.inputs.attached["pointers"];
  45184. if (pointers)
  45185. return pointers.pinchPrecision;
  45186. return 0;
  45187. },
  45188. set: function (value) {
  45189. var pointers = this.inputs.attached["pointers"];
  45190. if (pointers) {
  45191. pointers.pinchPrecision = value;
  45192. }
  45193. },
  45194. enumerable: true,
  45195. configurable: true
  45196. });
  45197. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45198. get: function () {
  45199. var pointers = this.inputs.attached["pointers"];
  45200. if (pointers)
  45201. return pointers.pinchDeltaPercentage;
  45202. return 0;
  45203. },
  45204. set: function (value) {
  45205. var pointers = this.inputs.attached["pointers"];
  45206. if (pointers) {
  45207. pointers.pinchDeltaPercentage = value;
  45208. }
  45209. },
  45210. enumerable: true,
  45211. configurable: true
  45212. });
  45213. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45214. get: function () {
  45215. var pointers = this.inputs.attached["pointers"];
  45216. if (pointers)
  45217. return pointers.panningSensibility;
  45218. return 0;
  45219. },
  45220. set: function (value) {
  45221. var pointers = this.inputs.attached["pointers"];
  45222. if (pointers) {
  45223. pointers.panningSensibility = value;
  45224. }
  45225. },
  45226. enumerable: true,
  45227. configurable: true
  45228. });
  45229. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45230. get: function () {
  45231. var keyboard = this.inputs.attached["keyboard"];
  45232. if (keyboard)
  45233. return keyboard.keysUp;
  45234. return [];
  45235. },
  45236. set: function (value) {
  45237. var keyboard = this.inputs.attached["keyboard"];
  45238. if (keyboard)
  45239. keyboard.keysUp = value;
  45240. },
  45241. enumerable: true,
  45242. configurable: true
  45243. });
  45244. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45245. get: function () {
  45246. var keyboard = this.inputs.attached["keyboard"];
  45247. if (keyboard)
  45248. return keyboard.keysDown;
  45249. return [];
  45250. },
  45251. set: function (value) {
  45252. var keyboard = this.inputs.attached["keyboard"];
  45253. if (keyboard)
  45254. keyboard.keysDown = value;
  45255. },
  45256. enumerable: true,
  45257. configurable: true
  45258. });
  45259. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45260. get: function () {
  45261. var keyboard = this.inputs.attached["keyboard"];
  45262. if (keyboard)
  45263. return keyboard.keysLeft;
  45264. return [];
  45265. },
  45266. set: function (value) {
  45267. var keyboard = this.inputs.attached["keyboard"];
  45268. if (keyboard)
  45269. keyboard.keysLeft = value;
  45270. },
  45271. enumerable: true,
  45272. configurable: true
  45273. });
  45274. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45275. get: function () {
  45276. var keyboard = this.inputs.attached["keyboard"];
  45277. if (keyboard)
  45278. return keyboard.keysRight;
  45279. return [];
  45280. },
  45281. set: function (value) {
  45282. var keyboard = this.inputs.attached["keyboard"];
  45283. if (keyboard)
  45284. keyboard.keysRight = value;
  45285. },
  45286. enumerable: true,
  45287. configurable: true
  45288. });
  45289. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45290. get: function () {
  45291. var mousewheel = this.inputs.attached["mousewheel"];
  45292. if (mousewheel)
  45293. return mousewheel.wheelPrecision;
  45294. return 0;
  45295. },
  45296. set: function (value) {
  45297. var mousewheel = this.inputs.attached["mousewheel"];
  45298. if (mousewheel)
  45299. mousewheel.wheelPrecision = value;
  45300. },
  45301. enumerable: true,
  45302. configurable: true
  45303. });
  45304. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45305. get: function () {
  45306. var mousewheel = this.inputs.attached["mousewheel"];
  45307. if (mousewheel)
  45308. return mousewheel.wheelDeltaPercentage;
  45309. return 0;
  45310. },
  45311. set: function (value) {
  45312. var mousewheel = this.inputs.attached["mousewheel"];
  45313. if (mousewheel)
  45314. mousewheel.wheelDeltaPercentage = value;
  45315. },
  45316. enumerable: true,
  45317. configurable: true
  45318. });
  45319. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45320. get: function () {
  45321. return this._bouncingBehavior;
  45322. },
  45323. enumerable: true,
  45324. configurable: true
  45325. });
  45326. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45327. get: function () {
  45328. return this._bouncingBehavior != null;
  45329. },
  45330. set: function (value) {
  45331. if (value === this.useBouncingBehavior) {
  45332. return;
  45333. }
  45334. if (value) {
  45335. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45336. this.addBehavior(this._bouncingBehavior);
  45337. }
  45338. else if (this._bouncingBehavior) {
  45339. this.removeBehavior(this._bouncingBehavior);
  45340. this._bouncingBehavior = null;
  45341. }
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45347. get: function () {
  45348. return this._framingBehavior;
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45354. get: function () {
  45355. return this._framingBehavior != null;
  45356. },
  45357. set: function (value) {
  45358. if (value === this.useFramingBehavior) {
  45359. return;
  45360. }
  45361. if (value) {
  45362. this._framingBehavior = new BABYLON.FramingBehavior();
  45363. this.addBehavior(this._framingBehavior);
  45364. }
  45365. else if (this._framingBehavior) {
  45366. this.removeBehavior(this._framingBehavior);
  45367. this._framingBehavior = null;
  45368. }
  45369. },
  45370. enumerable: true,
  45371. configurable: true
  45372. });
  45373. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45374. get: function () {
  45375. return this._autoRotationBehavior;
  45376. },
  45377. enumerable: true,
  45378. configurable: true
  45379. });
  45380. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45381. get: function () {
  45382. return this._autoRotationBehavior != null;
  45383. },
  45384. set: function (value) {
  45385. if (value === this.useAutoRotationBehavior) {
  45386. return;
  45387. }
  45388. if (value) {
  45389. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45390. this.addBehavior(this._autoRotationBehavior);
  45391. }
  45392. else if (this._autoRotationBehavior) {
  45393. this.removeBehavior(this._autoRotationBehavior);
  45394. this._autoRotationBehavior = null;
  45395. }
  45396. },
  45397. enumerable: true,
  45398. configurable: true
  45399. });
  45400. // Cache
  45401. ArcRotateCamera.prototype._initCache = function () {
  45402. _super.prototype._initCache.call(this);
  45403. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45404. this._cache.alpha = undefined;
  45405. this._cache.beta = undefined;
  45406. this._cache.radius = undefined;
  45407. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45408. };
  45409. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45410. if (!ignoreParentClass) {
  45411. _super.prototype._updateCache.call(this);
  45412. }
  45413. this._cache._target.copyFrom(this._getTargetPosition());
  45414. this._cache.alpha = this.alpha;
  45415. this._cache.beta = this.beta;
  45416. this._cache.radius = this.radius;
  45417. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45418. };
  45419. ArcRotateCamera.prototype._getTargetPosition = function () {
  45420. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45421. var pos = this._targetHost.getAbsolutePosition();
  45422. if (this._targetBoundingCenter) {
  45423. pos.addToRef(this._targetBoundingCenter, this._target);
  45424. }
  45425. else {
  45426. this._target.copyFrom(pos);
  45427. }
  45428. }
  45429. var lockedTargetPosition = this._getLockedTargetPosition();
  45430. if (lockedTargetPosition) {
  45431. return lockedTargetPosition;
  45432. }
  45433. return this._target;
  45434. };
  45435. ArcRotateCamera.prototype.storeState = function () {
  45436. this._storedAlpha = this.alpha;
  45437. this._storedBeta = this.beta;
  45438. this._storedRadius = this.radius;
  45439. this._storedTarget = this._getTargetPosition().clone();
  45440. return _super.prototype.storeState.call(this);
  45441. };
  45442. /**
  45443. * Restored camera state. You must call storeState() first
  45444. */
  45445. ArcRotateCamera.prototype._restoreStateValues = function () {
  45446. if (!_super.prototype._restoreStateValues.call(this)) {
  45447. return false;
  45448. }
  45449. this.alpha = this._storedAlpha;
  45450. this.beta = this._storedBeta;
  45451. this.radius = this._storedRadius;
  45452. this.setTarget(this._storedTarget.clone());
  45453. this.inertialAlphaOffset = 0;
  45454. this.inertialBetaOffset = 0;
  45455. this.inertialRadiusOffset = 0;
  45456. this.inertialPanningX = 0;
  45457. this.inertialPanningY = 0;
  45458. return true;
  45459. };
  45460. // Synchronized
  45461. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45462. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45463. return false;
  45464. return this._cache._target.equals(this._getTargetPosition())
  45465. && this._cache.alpha === this.alpha
  45466. && this._cache.beta === this.beta
  45467. && this._cache.radius === this.radius
  45468. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45469. };
  45470. // Methods
  45471. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45472. var _this = this;
  45473. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45474. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45475. this._useCtrlForPanning = useCtrlForPanning;
  45476. this._panningMouseButton = panningMouseButton;
  45477. this.inputs.attachElement(element, noPreventDefault);
  45478. this._reset = function () {
  45479. _this.inertialAlphaOffset = 0;
  45480. _this.inertialBetaOffset = 0;
  45481. _this.inertialRadiusOffset = 0;
  45482. _this.inertialPanningX = 0;
  45483. _this.inertialPanningY = 0;
  45484. };
  45485. };
  45486. ArcRotateCamera.prototype.detachControl = function (element) {
  45487. this.inputs.detachElement(element);
  45488. if (this._reset) {
  45489. this._reset();
  45490. }
  45491. };
  45492. ArcRotateCamera.prototype._checkInputs = function () {
  45493. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45494. if (this._collisionTriggered) {
  45495. return;
  45496. }
  45497. this.inputs.checkInputs();
  45498. // Inertia
  45499. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45500. if (this.getScene().useRightHandedSystem) {
  45501. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45502. }
  45503. else {
  45504. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45505. }
  45506. this.beta += this.inertialBetaOffset;
  45507. this.radius -= this.inertialRadiusOffset;
  45508. this.inertialAlphaOffset *= this.inertia;
  45509. this.inertialBetaOffset *= this.inertia;
  45510. this.inertialRadiusOffset *= this.inertia;
  45511. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45512. this.inertialAlphaOffset = 0;
  45513. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45514. this.inertialBetaOffset = 0;
  45515. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45516. this.inertialRadiusOffset = 0;
  45517. }
  45518. // Panning inertia
  45519. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45520. if (!this._localDirection) {
  45521. this._localDirection = BABYLON.Vector3.Zero();
  45522. this._transformedDirection = BABYLON.Vector3.Zero();
  45523. }
  45524. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45525. this._localDirection.multiplyInPlace(this.panningAxis);
  45526. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45527. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45528. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45529. if (!this.panningAxis.y) {
  45530. this._transformedDirection.y = 0;
  45531. }
  45532. if (!this._targetHost) {
  45533. if (this.panningDistanceLimit) {
  45534. this._transformedDirection.addInPlace(this._target);
  45535. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45536. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45537. this._target.copyFrom(this._transformedDirection);
  45538. }
  45539. }
  45540. else {
  45541. this._target.addInPlace(this._transformedDirection);
  45542. }
  45543. }
  45544. this.inertialPanningX *= this.panningInertia;
  45545. this.inertialPanningY *= this.panningInertia;
  45546. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45547. this.inertialPanningX = 0;
  45548. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45549. this.inertialPanningY = 0;
  45550. }
  45551. // Limits
  45552. this._checkLimits();
  45553. _super.prototype._checkInputs.call(this);
  45554. };
  45555. ArcRotateCamera.prototype._checkLimits = function () {
  45556. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45557. if (this.allowUpsideDown && this.beta > Math.PI) {
  45558. this.beta = this.beta - (2 * Math.PI);
  45559. }
  45560. }
  45561. else {
  45562. if (this.beta < this.lowerBetaLimit) {
  45563. this.beta = this.lowerBetaLimit;
  45564. }
  45565. }
  45566. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45567. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45568. this.beta = this.beta + (2 * Math.PI);
  45569. }
  45570. }
  45571. else {
  45572. if (this.beta > this.upperBetaLimit) {
  45573. this.beta = this.upperBetaLimit;
  45574. }
  45575. }
  45576. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45577. this.alpha = this.lowerAlphaLimit;
  45578. }
  45579. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45580. this.alpha = this.upperAlphaLimit;
  45581. }
  45582. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45583. this.radius = this.lowerRadiusLimit;
  45584. }
  45585. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45586. this.radius = this.upperRadiusLimit;
  45587. }
  45588. };
  45589. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45590. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45591. this.radius = this._computationVector.length();
  45592. if (this.radius === 0) {
  45593. this.radius = 0.0001; // Just to avoid division by zero
  45594. }
  45595. // Alpha
  45596. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45597. if (this._computationVector.z < 0) {
  45598. this.alpha = 2 * Math.PI - this.alpha;
  45599. }
  45600. // Beta
  45601. this.beta = Math.acos(this._computationVector.y / this.radius);
  45602. this._checkLimits();
  45603. };
  45604. ArcRotateCamera.prototype.setPosition = function (position) {
  45605. if (this.position.equals(position)) {
  45606. return;
  45607. }
  45608. this.position.copyFrom(position);
  45609. this.rebuildAnglesAndRadius();
  45610. };
  45611. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45612. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45613. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45614. if (target.getBoundingInfo) {
  45615. if (toBoundingCenter) {
  45616. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45617. }
  45618. else {
  45619. this._targetBoundingCenter = null;
  45620. }
  45621. this._targetHost = target;
  45622. this._target = this._getTargetPosition();
  45623. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45624. }
  45625. else {
  45626. var newTarget = target;
  45627. var currentTarget = this._getTargetPosition();
  45628. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45629. return;
  45630. }
  45631. this._targetHost = null;
  45632. this._target = newTarget;
  45633. this._targetBoundingCenter = null;
  45634. this.onMeshTargetChangedObservable.notifyObservers(null);
  45635. }
  45636. this.rebuildAnglesAndRadius();
  45637. };
  45638. ArcRotateCamera.prototype._getViewMatrix = function () {
  45639. // Compute
  45640. var cosa = Math.cos(this.alpha);
  45641. var sina = Math.sin(this.alpha);
  45642. var cosb = Math.cos(this.beta);
  45643. var sinb = Math.sin(this.beta);
  45644. if (sinb === 0) {
  45645. sinb = 0.0001;
  45646. }
  45647. var target = this._getTargetPosition();
  45648. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45649. target.addToRef(this._computationVector, this._newPosition);
  45650. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45651. if (!this._collider) {
  45652. this._collider = new BABYLON.Collider();
  45653. }
  45654. this._collider._radius = this.collisionRadius;
  45655. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45656. this._collisionTriggered = true;
  45657. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45658. }
  45659. else {
  45660. this.position.copyFrom(this._newPosition);
  45661. var up = this.upVector;
  45662. if (this.allowUpsideDown && sinb < 0) {
  45663. up = up.clone();
  45664. up = up.negate();
  45665. }
  45666. if (this.getScene().useRightHandedSystem) {
  45667. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45668. }
  45669. else {
  45670. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45671. }
  45672. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45673. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45674. }
  45675. this._currentTarget = target;
  45676. return this._viewMatrix;
  45677. };
  45678. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45679. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45680. meshes = meshes || this.getScene().meshes;
  45681. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45682. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45683. this.radius = distance * this.zoomOnFactor;
  45684. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45685. };
  45686. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45687. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45688. var meshesOrMinMaxVector;
  45689. var distance;
  45690. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45691. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45692. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45693. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45694. }
  45695. else {
  45696. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45697. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45698. distance = minMaxVectorAndDistance.distance;
  45699. }
  45700. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45701. if (!doNotUpdateMaxZ) {
  45702. this.maxZ = distance * 2;
  45703. }
  45704. };
  45705. /**
  45706. * @override
  45707. * Override Camera.createRigCamera
  45708. */
  45709. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45710. var alphaShift = 0;
  45711. switch (this.cameraRigMode) {
  45712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45714. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45715. case BABYLON.Camera.RIG_MODE_VR:
  45716. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45717. break;
  45718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45719. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45720. break;
  45721. }
  45722. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45723. rigCam._cameraRigParams = {};
  45724. return rigCam;
  45725. };
  45726. /**
  45727. * @override
  45728. * Override Camera._updateRigCameras
  45729. */
  45730. ArcRotateCamera.prototype._updateRigCameras = function () {
  45731. var camLeft = this._rigCameras[0];
  45732. var camRight = this._rigCameras[1];
  45733. camLeft.beta = camRight.beta = this.beta;
  45734. camLeft.radius = camRight.radius = this.radius;
  45735. switch (this.cameraRigMode) {
  45736. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45737. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45738. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45739. case BABYLON.Camera.RIG_MODE_VR:
  45740. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45741. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45742. break;
  45743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45744. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45745. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45746. break;
  45747. }
  45748. _super.prototype._updateRigCameras.call(this);
  45749. };
  45750. ArcRotateCamera.prototype.dispose = function () {
  45751. this.inputs.clear();
  45752. _super.prototype.dispose.call(this);
  45753. };
  45754. ArcRotateCamera.prototype.getClassName = function () {
  45755. return "ArcRotateCamera";
  45756. };
  45757. __decorate([
  45758. BABYLON.serialize()
  45759. ], ArcRotateCamera.prototype, "alpha", void 0);
  45760. __decorate([
  45761. BABYLON.serialize()
  45762. ], ArcRotateCamera.prototype, "beta", void 0);
  45763. __decorate([
  45764. BABYLON.serialize()
  45765. ], ArcRotateCamera.prototype, "radius", void 0);
  45766. __decorate([
  45767. BABYLON.serializeAsVector3("target")
  45768. ], ArcRotateCamera.prototype, "_target", void 0);
  45769. __decorate([
  45770. BABYLON.serialize()
  45771. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45772. __decorate([
  45773. BABYLON.serialize()
  45774. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45775. __decorate([
  45776. BABYLON.serialize()
  45777. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45778. __decorate([
  45779. BABYLON.serialize()
  45780. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45781. __decorate([
  45782. BABYLON.serialize()
  45783. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45784. __decorate([
  45785. BABYLON.serialize()
  45786. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45787. __decorate([
  45788. BABYLON.serialize()
  45789. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45790. __decorate([
  45791. BABYLON.serialize()
  45792. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45793. __decorate([
  45794. BABYLON.serialize()
  45795. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45796. __decorate([
  45797. BABYLON.serialize()
  45798. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45799. __decorate([
  45800. BABYLON.serialize()
  45801. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45802. __decorate([
  45803. BABYLON.serialize()
  45804. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45805. __decorate([
  45806. BABYLON.serialize()
  45807. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45808. __decorate([
  45809. BABYLON.serializeAsVector3()
  45810. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45811. __decorate([
  45812. BABYLON.serialize()
  45813. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45814. __decorate([
  45815. BABYLON.serialize()
  45816. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45817. __decorate([
  45818. BABYLON.serialize()
  45819. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45820. return ArcRotateCamera;
  45821. }(BABYLON.TargetCamera));
  45822. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45823. })(BABYLON || (BABYLON = {}));
  45824. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45825. "use strict";
  45826. var BABYLON;
  45827. (function (BABYLON) {
  45828. /**
  45829. * The HemisphericLight simulates the ambient environment light,
  45830. * so the passed direction is the light reflection direction, not the incoming direction.
  45831. */
  45832. var HemisphericLight = /** @class */ (function (_super) {
  45833. __extends(HemisphericLight, _super);
  45834. /**
  45835. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45836. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45837. * The HemisphericLight can't cast shadows.
  45838. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45839. * @param name The friendly name of the light
  45840. * @param direction The direction of the light reflection
  45841. * @param scene The scene the light belongs to
  45842. */
  45843. function HemisphericLight(name, direction, scene) {
  45844. var _this = _super.call(this, name, scene) || this;
  45845. /**
  45846. * The groundColor is the light in the opposite direction to the one specified during creation.
  45847. * 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.
  45848. */
  45849. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45850. _this.direction = direction || BABYLON.Vector3.Up();
  45851. return _this;
  45852. }
  45853. HemisphericLight.prototype._buildUniformLayout = function () {
  45854. this._uniformBuffer.addUniform("vLightData", 4);
  45855. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45856. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45857. this._uniformBuffer.addUniform("vLightGround", 3);
  45858. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45859. this._uniformBuffer.addUniform("depthValues", 2);
  45860. this._uniformBuffer.create();
  45861. };
  45862. /**
  45863. * Returns the string "HemisphericLight".
  45864. * @return The class name
  45865. */
  45866. HemisphericLight.prototype.getClassName = function () {
  45867. return "HemisphericLight";
  45868. };
  45869. /**
  45870. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45871. * Returns the updated direction.
  45872. * @param target The target the direction should point to
  45873. * @return The computed direction
  45874. */
  45875. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45876. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45877. return this.direction;
  45878. };
  45879. /**
  45880. * Returns the shadow generator associated to the light.
  45881. * @returns Always null for hemispheric lights because it does not support shadows.
  45882. */
  45883. HemisphericLight.prototype.getShadowGenerator = function () {
  45884. return null;
  45885. };
  45886. /**
  45887. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45888. * @param effect The effect to update
  45889. * @param lightIndex The index of the light in the effect to update
  45890. * @returns The hemispheric light
  45891. */
  45892. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45893. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45894. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45895. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45896. return this;
  45897. };
  45898. /**
  45899. * @ignore internal use only.
  45900. */
  45901. HemisphericLight.prototype._getWorldMatrix = function () {
  45902. if (!this._worldMatrix) {
  45903. this._worldMatrix = BABYLON.Matrix.Identity();
  45904. }
  45905. return this._worldMatrix;
  45906. };
  45907. /**
  45908. * Returns the integer 3.
  45909. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45910. */
  45911. HemisphericLight.prototype.getTypeID = function () {
  45912. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45913. };
  45914. __decorate([
  45915. BABYLON.serializeAsColor3()
  45916. ], HemisphericLight.prototype, "groundColor", void 0);
  45917. __decorate([
  45918. BABYLON.serializeAsVector3()
  45919. ], HemisphericLight.prototype, "direction", void 0);
  45920. return HemisphericLight;
  45921. }(BABYLON.Light));
  45922. BABYLON.HemisphericLight = HemisphericLight;
  45923. })(BABYLON || (BABYLON = {}));
  45924. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45925. "use strict";
  45926. var BABYLON;
  45927. (function (BABYLON) {
  45928. /**
  45929. * Base implementation IShadowLight
  45930. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45931. */
  45932. var ShadowLight = /** @class */ (function (_super) {
  45933. __extends(ShadowLight, _super);
  45934. function ShadowLight() {
  45935. var _this = _super !== null && _super.apply(this, arguments) || this;
  45936. _this._needProjectionMatrixCompute = true;
  45937. return _this;
  45938. }
  45939. ShadowLight.prototype._setPosition = function (value) {
  45940. this._position = value;
  45941. };
  45942. Object.defineProperty(ShadowLight.prototype, "position", {
  45943. /**
  45944. * Sets the position the shadow will be casted from. Also use as the light position for both
  45945. * point and spot lights.
  45946. */
  45947. get: function () {
  45948. return this._position;
  45949. },
  45950. /**
  45951. * Sets the position the shadow will be casted from. Also use as the light position for both
  45952. * point and spot lights.
  45953. */
  45954. set: function (value) {
  45955. this._setPosition(value);
  45956. },
  45957. enumerable: true,
  45958. configurable: true
  45959. });
  45960. ShadowLight.prototype._setDirection = function (value) {
  45961. this._direction = value;
  45962. };
  45963. Object.defineProperty(ShadowLight.prototype, "direction", {
  45964. /**
  45965. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45966. * Also use as the light direction on spot and directional lights.
  45967. */
  45968. get: function () {
  45969. return this._direction;
  45970. },
  45971. /**
  45972. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45973. * Also use as the light direction on spot and directional lights.
  45974. */
  45975. set: function (value) {
  45976. this._setDirection(value);
  45977. },
  45978. enumerable: true,
  45979. configurable: true
  45980. });
  45981. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45982. /**
  45983. * Gets the shadow projection clipping minimum z value.
  45984. */
  45985. get: function () {
  45986. return this._shadowMinZ;
  45987. },
  45988. /**
  45989. * Sets the shadow projection clipping minimum z value.
  45990. */
  45991. set: function (value) {
  45992. this._shadowMinZ = value;
  45993. this.forceProjectionMatrixCompute();
  45994. },
  45995. enumerable: true,
  45996. configurable: true
  45997. });
  45998. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45999. /**
  46000. * Sets the shadow projection clipping maximum z value.
  46001. */
  46002. get: function () {
  46003. return this._shadowMaxZ;
  46004. },
  46005. /**
  46006. * Gets the shadow projection clipping maximum z value.
  46007. */
  46008. set: function (value) {
  46009. this._shadowMaxZ = value;
  46010. this.forceProjectionMatrixCompute();
  46011. },
  46012. enumerable: true,
  46013. configurable: true
  46014. });
  46015. /**
  46016. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46017. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46018. */
  46019. ShadowLight.prototype.computeTransformedInformation = function () {
  46020. if (this.parent && this.parent.getWorldMatrix) {
  46021. if (!this.transformedPosition) {
  46022. this.transformedPosition = BABYLON.Vector3.Zero();
  46023. }
  46024. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46025. // In case the direction is present.
  46026. if (this.direction) {
  46027. if (!this.transformedDirection) {
  46028. this.transformedDirection = BABYLON.Vector3.Zero();
  46029. }
  46030. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46031. }
  46032. return true;
  46033. }
  46034. return false;
  46035. };
  46036. /**
  46037. * Return the depth scale used for the shadow map.
  46038. * @returns the depth scale.
  46039. */
  46040. ShadowLight.prototype.getDepthScale = function () {
  46041. return 50.0;
  46042. };
  46043. /**
  46044. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46045. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46046. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46047. */
  46048. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46049. return this.transformedDirection ? this.transformedDirection : this.direction;
  46050. };
  46051. /**
  46052. * Returns the ShadowLight absolute position in the World.
  46053. * @returns the position vector in world space
  46054. */
  46055. ShadowLight.prototype.getAbsolutePosition = function () {
  46056. return this.transformedPosition ? this.transformedPosition : this.position;
  46057. };
  46058. /**
  46059. * Sets the ShadowLight direction toward the passed target.
  46060. * @param target The point tot target in local space
  46061. * @returns the updated ShadowLight direction
  46062. */
  46063. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46064. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46065. return this.direction;
  46066. };
  46067. /**
  46068. * Returns the light rotation in euler definition.
  46069. * @returns the x y z rotation in local space.
  46070. */
  46071. ShadowLight.prototype.getRotation = function () {
  46072. this.direction.normalize();
  46073. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46074. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46075. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46076. };
  46077. /**
  46078. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46079. * @returns true if a cube texture needs to be use
  46080. */
  46081. ShadowLight.prototype.needCube = function () {
  46082. return false;
  46083. };
  46084. /**
  46085. * Detects if the projection matrix requires to be recomputed this frame.
  46086. * @returns true if it requires to be recomputed otherwise, false.
  46087. */
  46088. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46089. return this._needProjectionMatrixCompute;
  46090. };
  46091. /**
  46092. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46093. */
  46094. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46095. this._needProjectionMatrixCompute = true;
  46096. };
  46097. /**
  46098. * Get the world matrix of the sahdow lights.
  46099. * @ignore Internal Use Only
  46100. */
  46101. ShadowLight.prototype._getWorldMatrix = function () {
  46102. if (!this._worldMatrix) {
  46103. this._worldMatrix = BABYLON.Matrix.Identity();
  46104. }
  46105. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46106. return this._worldMatrix;
  46107. };
  46108. /**
  46109. * Gets the minZ used for shadow according to both the scene and the light.
  46110. * @param activeCamera The camera we are returning the min for
  46111. * @returns the depth min z
  46112. */
  46113. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46114. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46115. };
  46116. /**
  46117. * Gets the maxZ used for shadow according to both the scene and the light.
  46118. * @param activeCamera The camera we are returning the max for
  46119. * @returns the depth max z
  46120. */
  46121. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46122. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46123. };
  46124. /**
  46125. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46126. * @param matrix The materix to updated with the projection information
  46127. * @param viewMatrix The transform matrix of the light
  46128. * @param renderList The list of mesh to render in the map
  46129. * @returns The current light
  46130. */
  46131. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46132. if (this.customProjectionMatrixBuilder) {
  46133. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46134. }
  46135. else {
  46136. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46137. }
  46138. return this;
  46139. };
  46140. __decorate([
  46141. BABYLON.serializeAsVector3()
  46142. ], ShadowLight.prototype, "position", null);
  46143. __decorate([
  46144. BABYLON.serializeAsVector3()
  46145. ], ShadowLight.prototype, "direction", null);
  46146. __decorate([
  46147. BABYLON.serialize()
  46148. ], ShadowLight.prototype, "shadowMinZ", null);
  46149. __decorate([
  46150. BABYLON.serialize()
  46151. ], ShadowLight.prototype, "shadowMaxZ", null);
  46152. return ShadowLight;
  46153. }(BABYLON.Light));
  46154. BABYLON.ShadowLight = ShadowLight;
  46155. })(BABYLON || (BABYLON = {}));
  46156. //# sourceMappingURL=babylon.shadowLight.js.map
  46157. "use strict";
  46158. var BABYLON;
  46159. (function (BABYLON) {
  46160. /**
  46161. * A point light is a light defined by an unique point in world space.
  46162. * The light is emitted in every direction from this point.
  46163. * A good example of a point light is a standard light bulb.
  46164. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46165. */
  46166. var PointLight = /** @class */ (function (_super) {
  46167. __extends(PointLight, _super);
  46168. /**
  46169. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46170. * A PointLight emits the light in every direction.
  46171. * It can cast shadows.
  46172. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46173. * ```javascript
  46174. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46175. * ```
  46176. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46177. * @param name The light friendly name
  46178. * @param position The position of the point light in the scene
  46179. * @param scene The scene the lights belongs to
  46180. */
  46181. function PointLight(name, position, scene) {
  46182. var _this = _super.call(this, name, scene) || this;
  46183. _this._shadowAngle = Math.PI / 2;
  46184. _this.position = position;
  46185. return _this;
  46186. }
  46187. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46188. /**
  46189. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46190. * This specifies what angle the shadow will use to be created.
  46191. *
  46192. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46193. */
  46194. get: function () {
  46195. return this._shadowAngle;
  46196. },
  46197. /**
  46198. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46199. * This specifies what angle the shadow will use to be created.
  46200. *
  46201. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46202. */
  46203. set: function (value) {
  46204. this._shadowAngle = value;
  46205. this.forceProjectionMatrixCompute();
  46206. },
  46207. enumerable: true,
  46208. configurable: true
  46209. });
  46210. Object.defineProperty(PointLight.prototype, "direction", {
  46211. /**
  46212. * Gets the direction if it has been set.
  46213. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46214. */
  46215. get: function () {
  46216. return this._direction;
  46217. },
  46218. /**
  46219. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46220. */
  46221. set: function (value) {
  46222. var previousNeedCube = this.needCube();
  46223. this._direction = value;
  46224. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46225. this._shadowGenerator.recreateShadowMap();
  46226. }
  46227. },
  46228. enumerable: true,
  46229. configurable: true
  46230. });
  46231. /**
  46232. * Returns the string "PointLight"
  46233. * @returns the class name
  46234. */
  46235. PointLight.prototype.getClassName = function () {
  46236. return "PointLight";
  46237. };
  46238. /**
  46239. * Returns the integer 0.
  46240. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46241. */
  46242. PointLight.prototype.getTypeID = function () {
  46243. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46244. };
  46245. /**
  46246. * Specifies wether or not the shadowmap should be a cube texture.
  46247. * @returns true if the shadowmap needs to be a cube texture.
  46248. */
  46249. PointLight.prototype.needCube = function () {
  46250. return !this.direction;
  46251. };
  46252. /**
  46253. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46254. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46255. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46256. */
  46257. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46258. if (this.direction) {
  46259. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46260. }
  46261. else {
  46262. switch (faceIndex) {
  46263. case 0:
  46264. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46265. case 1:
  46266. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46267. case 2:
  46268. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46269. case 3:
  46270. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46271. case 4:
  46272. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46273. case 5:
  46274. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46275. }
  46276. }
  46277. return BABYLON.Vector3.Zero();
  46278. };
  46279. /**
  46280. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46281. * - fov = PI / 2
  46282. * - aspect ratio : 1.0
  46283. * - z-near and far equal to the active camera minZ and maxZ.
  46284. * Returns the PointLight.
  46285. */
  46286. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46287. var activeCamera = this.getScene().activeCamera;
  46288. if (!activeCamera) {
  46289. return;
  46290. }
  46291. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46292. };
  46293. PointLight.prototype._buildUniformLayout = function () {
  46294. this._uniformBuffer.addUniform("vLightData", 4);
  46295. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46296. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46297. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46298. this._uniformBuffer.addUniform("depthValues", 2);
  46299. this._uniformBuffer.create();
  46300. };
  46301. /**
  46302. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46303. * @param effect The effect to update
  46304. * @param lightIndex The index of the light in the effect to update
  46305. * @returns The point light
  46306. */
  46307. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46308. if (this.computeTransformedInformation()) {
  46309. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46310. return this;
  46311. }
  46312. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46313. return this;
  46314. };
  46315. __decorate([
  46316. BABYLON.serialize()
  46317. ], PointLight.prototype, "shadowAngle", null);
  46318. return PointLight;
  46319. }(BABYLON.ShadowLight));
  46320. BABYLON.PointLight = PointLight;
  46321. })(BABYLON || (BABYLON = {}));
  46322. //# sourceMappingURL=babylon.pointLight.js.map
  46323. "use strict";
  46324. var BABYLON;
  46325. (function (BABYLON) {
  46326. /**
  46327. * A directional light is defined by a direction (what a surprise!).
  46328. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46329. * 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.
  46330. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46331. */
  46332. var DirectionalLight = /** @class */ (function (_super) {
  46333. __extends(DirectionalLight, _super);
  46334. /**
  46335. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46336. * The directional light is emitted from everywhere in the given direction.
  46337. * It can cast shawdows.
  46338. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46339. * @param name The friendly name of the light
  46340. * @param direction The direction of the light
  46341. * @param scene The scene the light belongs to
  46342. */
  46343. function DirectionalLight(name, direction, scene) {
  46344. var _this = _super.call(this, name, scene) || this;
  46345. _this._shadowFrustumSize = 0;
  46346. _this._shadowOrthoScale = 0.1;
  46347. /**
  46348. * Automatically compute the projection matrix to best fit (including all the casters)
  46349. * on each frame.
  46350. */
  46351. _this.autoUpdateExtends = true;
  46352. // Cache
  46353. _this._orthoLeft = Number.MAX_VALUE;
  46354. _this._orthoRight = Number.MIN_VALUE;
  46355. _this._orthoTop = Number.MIN_VALUE;
  46356. _this._orthoBottom = Number.MAX_VALUE;
  46357. _this.position = direction.scale(-1.0);
  46358. _this.direction = direction;
  46359. return _this;
  46360. }
  46361. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46362. /**
  46363. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46364. */
  46365. get: function () {
  46366. return this._shadowFrustumSize;
  46367. },
  46368. /**
  46369. * Specifies a fix frustum size for the shadow generation.
  46370. */
  46371. set: function (value) {
  46372. this._shadowFrustumSize = value;
  46373. this.forceProjectionMatrixCompute();
  46374. },
  46375. enumerable: true,
  46376. configurable: true
  46377. });
  46378. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46379. /**
  46380. * Gets the shadow projection scale against the optimal computed one.
  46381. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46382. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46383. */
  46384. get: function () {
  46385. return this._shadowOrthoScale;
  46386. },
  46387. /**
  46388. * Sets the shadow projection scale against the optimal computed one.
  46389. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46390. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46391. */
  46392. set: function (value) {
  46393. this._shadowOrthoScale = value;
  46394. this.forceProjectionMatrixCompute();
  46395. },
  46396. enumerable: true,
  46397. configurable: true
  46398. });
  46399. /**
  46400. * Returns the string "DirectionalLight".
  46401. * @return The class name
  46402. */
  46403. DirectionalLight.prototype.getClassName = function () {
  46404. return "DirectionalLight";
  46405. };
  46406. /**
  46407. * Returns the integer 1.
  46408. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46409. */
  46410. DirectionalLight.prototype.getTypeID = function () {
  46411. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46412. };
  46413. /**
  46414. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46415. * Returns the DirectionalLight Shadow projection matrix.
  46416. */
  46417. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46418. if (this.shadowFrustumSize > 0) {
  46419. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46420. }
  46421. else {
  46422. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46423. }
  46424. };
  46425. /**
  46426. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46427. * Returns the DirectionalLight Shadow projection matrix.
  46428. */
  46429. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46430. var activeCamera = this.getScene().activeCamera;
  46431. if (!activeCamera) {
  46432. return;
  46433. }
  46434. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46435. };
  46436. /**
  46437. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46438. * Returns the DirectionalLight Shadow projection matrix.
  46439. */
  46440. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46441. var activeCamera = this.getScene().activeCamera;
  46442. if (!activeCamera) {
  46443. return;
  46444. }
  46445. // Check extends
  46446. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46447. var tempVector3 = BABYLON.Vector3.Zero();
  46448. this._orthoLeft = Number.MAX_VALUE;
  46449. this._orthoRight = Number.MIN_VALUE;
  46450. this._orthoTop = Number.MIN_VALUE;
  46451. this._orthoBottom = Number.MAX_VALUE;
  46452. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46453. var mesh = renderList[meshIndex];
  46454. if (!mesh) {
  46455. continue;
  46456. }
  46457. var boundingInfo = mesh.getBoundingInfo();
  46458. var boundingBox = boundingInfo.boundingBox;
  46459. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46460. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46461. if (tempVector3.x < this._orthoLeft)
  46462. this._orthoLeft = tempVector3.x;
  46463. if (tempVector3.y < this._orthoBottom)
  46464. this._orthoBottom = tempVector3.y;
  46465. if (tempVector3.x > this._orthoRight)
  46466. this._orthoRight = tempVector3.x;
  46467. if (tempVector3.y > this._orthoTop)
  46468. this._orthoTop = tempVector3.y;
  46469. }
  46470. }
  46471. }
  46472. var xOffset = this._orthoRight - this._orthoLeft;
  46473. var yOffset = this._orthoTop - this._orthoBottom;
  46474. 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);
  46475. };
  46476. DirectionalLight.prototype._buildUniformLayout = function () {
  46477. this._uniformBuffer.addUniform("vLightData", 4);
  46478. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46479. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46480. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46481. this._uniformBuffer.addUniform("depthValues", 2);
  46482. this._uniformBuffer.create();
  46483. };
  46484. /**
  46485. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46486. * @param effect The effect to update
  46487. * @param lightIndex The index of the light in the effect to update
  46488. * @returns The directional light
  46489. */
  46490. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46491. if (this.computeTransformedInformation()) {
  46492. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46493. return this;
  46494. }
  46495. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46496. return this;
  46497. };
  46498. /**
  46499. * Gets the minZ used for shadow according to both the scene and the light.
  46500. *
  46501. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46502. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46503. * @param activeCamera The camera we are returning the min for
  46504. * @returns the depth min z
  46505. */
  46506. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46507. return 1;
  46508. };
  46509. /**
  46510. * Gets the maxZ used for shadow according to both the scene and the light.
  46511. *
  46512. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46513. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46514. * @param activeCamera The camera we are returning the max for
  46515. * @returns the depth max z
  46516. */
  46517. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46518. return 1;
  46519. };
  46520. __decorate([
  46521. BABYLON.serialize()
  46522. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46523. __decorate([
  46524. BABYLON.serialize()
  46525. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46526. __decorate([
  46527. BABYLON.serialize()
  46528. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46529. return DirectionalLight;
  46530. }(BABYLON.ShadowLight));
  46531. BABYLON.DirectionalLight = DirectionalLight;
  46532. })(BABYLON || (BABYLON = {}));
  46533. //# sourceMappingURL=babylon.directionalLight.js.map
  46534. "use strict";
  46535. var BABYLON;
  46536. (function (BABYLON) {
  46537. /**
  46538. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46539. * These values define a cone of light starting from the position, emitting toward the direction.
  46540. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46541. * and the exponent defines the speed of the decay of the light with distance (reach).
  46542. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46543. */
  46544. var SpotLight = /** @class */ (function (_super) {
  46545. __extends(SpotLight, _super);
  46546. /**
  46547. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46548. * It can cast shadows.
  46549. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46550. * @param name The light friendly name
  46551. * @param position The position of the spot light in the scene
  46552. * @param direction The direction of the light in the scene
  46553. * @param angle The cone angle of the light in Radians
  46554. * @param exponent The light decay speed with the distance from the emission spot
  46555. * @param scene The scene the lights belongs to
  46556. */
  46557. function SpotLight(name, position, direction, angle, exponent, scene) {
  46558. var _this = _super.call(this, name, scene) || this;
  46559. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46560. _this._projectionTextureLightNear = 1e-6;
  46561. _this._projectionTextureLightFar = 1000.0;
  46562. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46563. _this._projectionTextureViewLightDirty = true;
  46564. _this._projectionTextureProjectionLightDirty = true;
  46565. _this._projectionTextureDirty = true;
  46566. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46567. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46568. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46569. _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);
  46570. _this.position = position;
  46571. _this.direction = direction;
  46572. _this.angle = angle;
  46573. _this.exponent = exponent;
  46574. return _this;
  46575. }
  46576. Object.defineProperty(SpotLight.prototype, "angle", {
  46577. /**
  46578. * Gets the cone angle of the spot light in Radians.
  46579. */
  46580. get: function () {
  46581. return this._angle;
  46582. },
  46583. /**
  46584. * Sets the cone angle of the spot light in Radians.
  46585. */
  46586. set: function (value) {
  46587. this._angle = value;
  46588. this._projectionTextureProjectionLightDirty = true;
  46589. this.forceProjectionMatrixCompute();
  46590. },
  46591. enumerable: true,
  46592. configurable: true
  46593. });
  46594. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46595. /**
  46596. * Allows scaling the angle of the light for shadow generation only.
  46597. */
  46598. get: function () {
  46599. return this._shadowAngleScale;
  46600. },
  46601. /**
  46602. * Allows scaling the angle of the light for shadow generation only.
  46603. */
  46604. set: function (value) {
  46605. this._shadowAngleScale = value;
  46606. this.forceProjectionMatrixCompute();
  46607. },
  46608. enumerable: true,
  46609. configurable: true
  46610. });
  46611. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46612. /**
  46613. * Allows reading the projecton texture
  46614. */
  46615. get: function () {
  46616. return this._projectionTextureMatrix;
  46617. },
  46618. enumerable: true,
  46619. configurable: true
  46620. });
  46621. ;
  46622. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46623. /**
  46624. * Gets the near clip of the Spotlight for texture projection.
  46625. */
  46626. get: function () {
  46627. return this._projectionTextureLightNear;
  46628. },
  46629. /**
  46630. * Sets the near clip of the Spotlight for texture projection.
  46631. */
  46632. set: function (value) {
  46633. this._projectionTextureLightNear = value;
  46634. this._projectionTextureProjectionLightDirty = true;
  46635. },
  46636. enumerable: true,
  46637. configurable: true
  46638. });
  46639. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46640. /**
  46641. * Gets the far clip of the Spotlight for texture projection.
  46642. */
  46643. get: function () {
  46644. return this._projectionTextureLightFar;
  46645. },
  46646. /**
  46647. * Sets the far clip of the Spotlight for texture projection.
  46648. */
  46649. set: function (value) {
  46650. this._projectionTextureLightFar = value;
  46651. this._projectionTextureProjectionLightDirty = true;
  46652. },
  46653. enumerable: true,
  46654. configurable: true
  46655. });
  46656. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46657. /**
  46658. * Gets the Up vector of the Spotlight for texture projection.
  46659. */
  46660. get: function () {
  46661. return this._projectionTextureUpDirection;
  46662. },
  46663. /**
  46664. * Sets the Up vector of the Spotlight for texture projection.
  46665. */
  46666. set: function (value) {
  46667. this._projectionTextureUpDirection = value;
  46668. this._projectionTextureProjectionLightDirty = true;
  46669. },
  46670. enumerable: true,
  46671. configurable: true
  46672. });
  46673. ;
  46674. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46675. /**
  46676. * Gets the projection texture of the light.
  46677. */
  46678. get: function () {
  46679. return this._projectionTexture;
  46680. },
  46681. /**
  46682. * Sets the projection texture of the light.
  46683. */
  46684. set: function (value) {
  46685. this._projectionTexture = value;
  46686. this._projectionTextureDirty = true;
  46687. },
  46688. enumerable: true,
  46689. configurable: true
  46690. });
  46691. /**
  46692. * Returns the string "SpotLight".
  46693. * @returns the class name
  46694. */
  46695. SpotLight.prototype.getClassName = function () {
  46696. return "SpotLight";
  46697. };
  46698. /**
  46699. * Returns the integer 2.
  46700. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46701. */
  46702. SpotLight.prototype.getTypeID = function () {
  46703. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46704. };
  46705. /**
  46706. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46707. */
  46708. SpotLight.prototype._setDirection = function (value) {
  46709. _super.prototype._setDirection.call(this, value);
  46710. this._projectionTextureViewLightDirty = true;
  46711. };
  46712. /**
  46713. * Overrides the position setter to recompute the projection texture view light Matrix.
  46714. */
  46715. SpotLight.prototype._setPosition = function (value) {
  46716. _super.prototype._setPosition.call(this, value);
  46717. this._projectionTextureViewLightDirty = true;
  46718. };
  46719. /**
  46720. * 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.
  46721. * Returns the SpotLight.
  46722. */
  46723. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46724. var activeCamera = this.getScene().activeCamera;
  46725. if (!activeCamera) {
  46726. return;
  46727. }
  46728. this._shadowAngleScale = this._shadowAngleScale || 1;
  46729. var angle = this._shadowAngleScale * this._angle;
  46730. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46731. };
  46732. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46733. this._projectionTextureViewLightDirty = false;
  46734. this._projectionTextureDirty = true;
  46735. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46736. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46737. };
  46738. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46739. this._projectionTextureProjectionLightDirty = false;
  46740. this._projectionTextureDirty = true;
  46741. var light_far = this.projectionTextureLightFar;
  46742. var light_near = this.projectionTextureLightNear;
  46743. var P = light_far / (light_far - light_near);
  46744. var Q = -P * light_near;
  46745. var S = 1.0 / Math.tan(this._angle / 2.0);
  46746. var A = 1.0;
  46747. 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);
  46748. };
  46749. /**
  46750. * Main function for light texture projection matrix computing.
  46751. */
  46752. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46753. this._projectionTextureDirty = false;
  46754. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46755. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46756. };
  46757. SpotLight.prototype._buildUniformLayout = function () {
  46758. this._uniformBuffer.addUniform("vLightData", 4);
  46759. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46760. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46761. this._uniformBuffer.addUniform("vLightDirection", 3);
  46762. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46763. this._uniformBuffer.addUniform("depthValues", 2);
  46764. this._uniformBuffer.create();
  46765. };
  46766. /**
  46767. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46768. * @param effect The effect to update
  46769. * @param lightIndex The index of the light in the effect to update
  46770. * @returns The spot light
  46771. */
  46772. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46773. var normalizeDirection;
  46774. if (this.computeTransformedInformation()) {
  46775. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46776. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46777. }
  46778. else {
  46779. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46780. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46781. }
  46782. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46783. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46784. if (this._projectionTextureViewLightDirty) {
  46785. this._computeProjectionTextureViewLightMatrix();
  46786. }
  46787. if (this._projectionTextureProjectionLightDirty) {
  46788. this._computeProjectionTextureProjectionLightMatrix();
  46789. }
  46790. if (this._projectionTextureDirty) {
  46791. this._computeProjectionTextureMatrix();
  46792. }
  46793. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46794. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46795. }
  46796. return this;
  46797. };
  46798. /**
  46799. * Disposes the light and the associated resources.
  46800. */
  46801. SpotLight.prototype.dispose = function () {
  46802. _super.prototype.dispose.call(this);
  46803. if (this._projectionTexture) {
  46804. this._projectionTexture.dispose();
  46805. }
  46806. };
  46807. __decorate([
  46808. BABYLON.serialize()
  46809. ], SpotLight.prototype, "angle", null);
  46810. __decorate([
  46811. BABYLON.serialize()
  46812. ], SpotLight.prototype, "shadowAngleScale", null);
  46813. __decorate([
  46814. BABYLON.serialize()
  46815. ], SpotLight.prototype, "exponent", void 0);
  46816. __decorate([
  46817. BABYLON.serialize()
  46818. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46819. __decorate([
  46820. BABYLON.serialize()
  46821. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46822. __decorate([
  46823. BABYLON.serialize()
  46824. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46825. __decorate([
  46826. BABYLON.serializeAsTexture("projectedLightTexture")
  46827. ], SpotLight.prototype, "_projectionTexture", void 0);
  46828. return SpotLight;
  46829. }(BABYLON.ShadowLight));
  46830. BABYLON.SpotLight = SpotLight;
  46831. })(BABYLON || (BABYLON = {}));
  46832. //# sourceMappingURL=babylon.spotLight.js.map
  46833. "use strict";
  46834. var BABYLON;
  46835. (function (BABYLON) {
  46836. /**
  46837. * Class used to override all child animations of a given target
  46838. */
  46839. var AnimationPropertiesOverride = /** @class */ (function () {
  46840. function AnimationPropertiesOverride() {
  46841. /**
  46842. * Gets or sets a value indicating if animation blending must be used
  46843. */
  46844. this.enableBlending = false;
  46845. /**
  46846. * Gets or sets the blending speed to use when enableBlending is true
  46847. */
  46848. this.blendingSpeed = 0.01;
  46849. /**
  46850. * Gets or sets the default loop mode to use
  46851. */
  46852. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46853. }
  46854. return AnimationPropertiesOverride;
  46855. }());
  46856. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46857. })(BABYLON || (BABYLON = {}));
  46858. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46859. "use strict";
  46860. var BABYLON;
  46861. (function (BABYLON) {
  46862. var AnimationRange = /** @class */ (function () {
  46863. function AnimationRange(name, from, to) {
  46864. this.name = name;
  46865. this.from = from;
  46866. this.to = to;
  46867. }
  46868. AnimationRange.prototype.clone = function () {
  46869. return new AnimationRange(this.name, this.from, this.to);
  46870. };
  46871. return AnimationRange;
  46872. }());
  46873. BABYLON.AnimationRange = AnimationRange;
  46874. /**
  46875. * Composed of a frame, and an action function
  46876. */
  46877. var AnimationEvent = /** @class */ (function () {
  46878. function AnimationEvent(frame, action, onlyOnce) {
  46879. this.frame = frame;
  46880. this.action = action;
  46881. this.onlyOnce = onlyOnce;
  46882. this.isDone = false;
  46883. }
  46884. return AnimationEvent;
  46885. }());
  46886. BABYLON.AnimationEvent = AnimationEvent;
  46887. var PathCursor = /** @class */ (function () {
  46888. function PathCursor(path) {
  46889. this.path = path;
  46890. this._onchange = new Array();
  46891. this.value = 0;
  46892. this.animations = new Array();
  46893. }
  46894. PathCursor.prototype.getPoint = function () {
  46895. var point = this.path.getPointAtLengthPosition(this.value);
  46896. return new BABYLON.Vector3(point.x, 0, point.y);
  46897. };
  46898. PathCursor.prototype.moveAhead = function (step) {
  46899. if (step === void 0) { step = 0.002; }
  46900. this.move(step);
  46901. return this;
  46902. };
  46903. PathCursor.prototype.moveBack = function (step) {
  46904. if (step === void 0) { step = 0.002; }
  46905. this.move(-step);
  46906. return this;
  46907. };
  46908. PathCursor.prototype.move = function (step) {
  46909. if (Math.abs(step) > 1) {
  46910. throw "step size should be less than 1.";
  46911. }
  46912. this.value += step;
  46913. this.ensureLimits();
  46914. this.raiseOnChange();
  46915. return this;
  46916. };
  46917. PathCursor.prototype.ensureLimits = function () {
  46918. while (this.value > 1) {
  46919. this.value -= 1;
  46920. }
  46921. while (this.value < 0) {
  46922. this.value += 1;
  46923. }
  46924. return this;
  46925. };
  46926. // used by animation engine
  46927. PathCursor.prototype.raiseOnChange = function () {
  46928. var _this = this;
  46929. this._onchange.forEach(function (f) { return f(_this); });
  46930. return this;
  46931. };
  46932. PathCursor.prototype.onchange = function (f) {
  46933. this._onchange.push(f);
  46934. return this;
  46935. };
  46936. return PathCursor;
  46937. }());
  46938. BABYLON.PathCursor = PathCursor;
  46939. var AnimationKeyInterpolation;
  46940. (function (AnimationKeyInterpolation) {
  46941. /**
  46942. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46943. */
  46944. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46945. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46946. var Animation = /** @class */ (function () {
  46947. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46948. this.name = name;
  46949. this.targetProperty = targetProperty;
  46950. this.framePerSecond = framePerSecond;
  46951. this.dataType = dataType;
  46952. this.loopMode = loopMode;
  46953. this.enableBlending = enableBlending;
  46954. this._runtimeAnimations = new Array();
  46955. // The set of event that will be linked to this animation
  46956. this._events = new Array();
  46957. this.blendingSpeed = 0.01;
  46958. this._ranges = {};
  46959. this.targetPropertyPath = targetProperty.split(".");
  46960. this.dataType = dataType;
  46961. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46962. }
  46963. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46964. var dataType = undefined;
  46965. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46966. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46967. }
  46968. else if (from instanceof BABYLON.Quaternion) {
  46969. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46970. }
  46971. else if (from instanceof BABYLON.Vector3) {
  46972. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46973. }
  46974. else if (from instanceof BABYLON.Vector2) {
  46975. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46976. }
  46977. else if (from instanceof BABYLON.Color3) {
  46978. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46979. }
  46980. else if (from instanceof BABYLON.Size) {
  46981. dataType = Animation.ANIMATIONTYPE_SIZE;
  46982. }
  46983. if (dataType == undefined) {
  46984. return null;
  46985. }
  46986. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46987. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46988. animation.setKeys(keys);
  46989. if (easingFunction !== undefined) {
  46990. animation.setEasingFunction(easingFunction);
  46991. }
  46992. return animation;
  46993. };
  46994. /**
  46995. * Sets up an animation.
  46996. * @param property the property to animate
  46997. * @param animationType the animation type to apply
  46998. * @param easingFunction the easing function used in the animation
  46999. * @returns The created animation
  47000. */
  47001. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  47002. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  47003. animation.setEasingFunction(easingFunction);
  47004. return animation;
  47005. };
  47006. /**
  47007. * Create and start an animation on a node
  47008. * @param {string} name defines the name of the global animation that will be run on all nodes
  47009. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47010. * @param {string} targetProperty defines property to animate
  47011. * @param {number} framePerSecond defines the number of frame per second yo use
  47012. * @param {number} totalFrame defines the number of frames in total
  47013. * @param {any} from defines the initial value
  47014. * @param {any} to defines the final value
  47015. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47016. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47017. * @param onAnimationEnd defines the callback to call when animation end
  47018. * @returns the animatable created for this animation
  47019. */
  47020. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47021. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47022. if (!animation) {
  47023. return null;
  47024. }
  47025. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47026. };
  47027. /**
  47028. * Create and start an animation on a node and its descendants
  47029. * @param {string} name defines the name of the global animation that will be run on all nodes
  47030. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47031. * @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.
  47032. * @param {string} targetProperty defines property to animate
  47033. * @param {number} framePerSecond defines the number of frame per second yo use
  47034. * @param {number} totalFrame defines the number of frames in total
  47035. * @param {any} from defines the initial value
  47036. * @param {any} to defines the final value
  47037. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47038. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47039. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47040. * @returns the list of animatables created for all nodes
  47041. * @example https://www.babylonjs-playground.com/#MH0VLI
  47042. */
  47043. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47044. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47045. if (!animation) {
  47046. return null;
  47047. }
  47048. var scene = node.getScene();
  47049. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47050. };
  47051. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47052. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47053. if (!animation) {
  47054. return null;
  47055. }
  47056. node.animations.push(animation);
  47057. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47058. };
  47059. /**
  47060. * Transition property of the Camera to the target Value.
  47061. * @param property The property to transition
  47062. * @param targetValue The target Value of the property
  47063. * @param host The object where the property to animate belongs
  47064. * @param scene Scene used to run the animation
  47065. * @param frameRate Framerate (in frame/s) to use
  47066. * @param transition The transition type we want to use
  47067. * @param duration The duration of the animation, in milliseconds
  47068. * @param onAnimationEnd Call back trigger at the end of the animation.
  47069. */
  47070. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47071. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47072. if (duration <= 0) {
  47073. host[property] = targetValue;
  47074. if (onAnimationEnd) {
  47075. onAnimationEnd();
  47076. }
  47077. return null;
  47078. }
  47079. var endFrame = frameRate * (duration / 1000);
  47080. transition.setKeys([{
  47081. frame: 0,
  47082. value: host[property].clone ? host[property].clone() : host[property]
  47083. },
  47084. {
  47085. frame: endFrame,
  47086. value: targetValue
  47087. }]);
  47088. if (!host.animations) {
  47089. host.animations = [];
  47090. }
  47091. host.animations.push(transition);
  47092. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47093. animation.onAnimationEnd = onAnimationEnd;
  47094. return animation;
  47095. };
  47096. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47097. /**
  47098. * Return the array of runtime animations currently using this animation
  47099. */
  47100. get: function () {
  47101. return this._runtimeAnimations;
  47102. },
  47103. enumerable: true,
  47104. configurable: true
  47105. });
  47106. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47107. get: function () {
  47108. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47109. var runtimeAnimation = _a[_i];
  47110. if (!runtimeAnimation.isStopped) {
  47111. return true;
  47112. }
  47113. }
  47114. return false;
  47115. },
  47116. enumerable: true,
  47117. configurable: true
  47118. });
  47119. // Methods
  47120. /**
  47121. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47122. */
  47123. Animation.prototype.toString = function (fullDetails) {
  47124. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47125. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47126. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47127. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47128. if (fullDetails) {
  47129. ret += ", Ranges: {";
  47130. var first = true;
  47131. for (var name in this._ranges) {
  47132. if (first) {
  47133. ret += ", ";
  47134. first = false;
  47135. }
  47136. ret += name;
  47137. }
  47138. ret += "}";
  47139. }
  47140. return ret;
  47141. };
  47142. /**
  47143. * Add an event to this animation.
  47144. */
  47145. Animation.prototype.addEvent = function (event) {
  47146. this._events.push(event);
  47147. };
  47148. /**
  47149. * Remove all events found at the given frame
  47150. * @param frame
  47151. */
  47152. Animation.prototype.removeEvents = function (frame) {
  47153. for (var index = 0; index < this._events.length; index++) {
  47154. if (this._events[index].frame === frame) {
  47155. this._events.splice(index, 1);
  47156. index--;
  47157. }
  47158. }
  47159. };
  47160. Animation.prototype.getEvents = function () {
  47161. return this._events;
  47162. };
  47163. Animation.prototype.createRange = function (name, from, to) {
  47164. // check name not already in use; could happen for bones after serialized
  47165. if (!this._ranges[name]) {
  47166. this._ranges[name] = new AnimationRange(name, from, to);
  47167. }
  47168. };
  47169. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47170. if (deleteFrames === void 0) { deleteFrames = true; }
  47171. var range = this._ranges[name];
  47172. if (!range) {
  47173. return;
  47174. }
  47175. if (deleteFrames) {
  47176. var from = range.from;
  47177. var to = range.to;
  47178. // this loop MUST go high to low for multiple splices to work
  47179. for (var key = this._keys.length - 1; key >= 0; key--) {
  47180. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47181. this._keys.splice(key, 1);
  47182. }
  47183. }
  47184. }
  47185. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47186. };
  47187. Animation.prototype.getRange = function (name) {
  47188. return this._ranges[name];
  47189. };
  47190. Animation.prototype.getKeys = function () {
  47191. return this._keys;
  47192. };
  47193. Animation.prototype.getHighestFrame = function () {
  47194. var ret = 0;
  47195. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47196. if (ret < this._keys[key].frame) {
  47197. ret = this._keys[key].frame;
  47198. }
  47199. }
  47200. return ret;
  47201. };
  47202. Animation.prototype.getEasingFunction = function () {
  47203. return this._easingFunction;
  47204. };
  47205. Animation.prototype.setEasingFunction = function (easingFunction) {
  47206. this._easingFunction = easingFunction;
  47207. };
  47208. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47209. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47210. };
  47211. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47212. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47213. };
  47214. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47215. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47216. };
  47217. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47218. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47219. };
  47220. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47221. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47222. };
  47223. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47224. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47225. };
  47226. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47227. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47228. };
  47229. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47230. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47231. };
  47232. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47233. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47234. };
  47235. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47236. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47237. };
  47238. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47239. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47240. };
  47241. Animation.prototype.clone = function () {
  47242. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47243. clone.enableBlending = this.enableBlending;
  47244. clone.blendingSpeed = this.blendingSpeed;
  47245. if (this._keys) {
  47246. clone.setKeys(this._keys);
  47247. }
  47248. if (this._ranges) {
  47249. clone._ranges = {};
  47250. for (var name in this._ranges) {
  47251. var range = this._ranges[name];
  47252. if (!range) {
  47253. continue;
  47254. }
  47255. clone._ranges[name] = range.clone();
  47256. }
  47257. }
  47258. return clone;
  47259. };
  47260. Animation.prototype.setKeys = function (values) {
  47261. this._keys = values.slice(0);
  47262. };
  47263. Animation.prototype.serialize = function () {
  47264. var serializationObject = {};
  47265. serializationObject.name = this.name;
  47266. serializationObject.property = this.targetProperty;
  47267. serializationObject.framePerSecond = this.framePerSecond;
  47268. serializationObject.dataType = this.dataType;
  47269. serializationObject.loopBehavior = this.loopMode;
  47270. serializationObject.enableBlending = this.enableBlending;
  47271. serializationObject.blendingSpeed = this.blendingSpeed;
  47272. var dataType = this.dataType;
  47273. serializationObject.keys = [];
  47274. var keys = this.getKeys();
  47275. for (var index = 0; index < keys.length; index++) {
  47276. var animationKey = keys[index];
  47277. var key = {};
  47278. key.frame = animationKey.frame;
  47279. switch (dataType) {
  47280. case Animation.ANIMATIONTYPE_FLOAT:
  47281. key.values = [animationKey.value];
  47282. break;
  47283. case Animation.ANIMATIONTYPE_QUATERNION:
  47284. case Animation.ANIMATIONTYPE_MATRIX:
  47285. case Animation.ANIMATIONTYPE_VECTOR3:
  47286. case Animation.ANIMATIONTYPE_COLOR3:
  47287. key.values = animationKey.value.asArray();
  47288. break;
  47289. }
  47290. serializationObject.keys.push(key);
  47291. }
  47292. serializationObject.ranges = [];
  47293. for (var name in this._ranges) {
  47294. var source = this._ranges[name];
  47295. if (!source) {
  47296. continue;
  47297. }
  47298. var range = {};
  47299. range.name = name;
  47300. range.from = source.from;
  47301. range.to = source.to;
  47302. serializationObject.ranges.push(range);
  47303. }
  47304. return serializationObject;
  47305. };
  47306. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47307. get: function () {
  47308. return Animation._ANIMATIONTYPE_FLOAT;
  47309. },
  47310. enumerable: true,
  47311. configurable: true
  47312. });
  47313. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47314. get: function () {
  47315. return Animation._ANIMATIONTYPE_VECTOR3;
  47316. },
  47317. enumerable: true,
  47318. configurable: true
  47319. });
  47320. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47321. get: function () {
  47322. return Animation._ANIMATIONTYPE_VECTOR2;
  47323. },
  47324. enumerable: true,
  47325. configurable: true
  47326. });
  47327. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47328. get: function () {
  47329. return Animation._ANIMATIONTYPE_SIZE;
  47330. },
  47331. enumerable: true,
  47332. configurable: true
  47333. });
  47334. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47335. get: function () {
  47336. return Animation._ANIMATIONTYPE_QUATERNION;
  47337. },
  47338. enumerable: true,
  47339. configurable: true
  47340. });
  47341. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47342. get: function () {
  47343. return Animation._ANIMATIONTYPE_MATRIX;
  47344. },
  47345. enumerable: true,
  47346. configurable: true
  47347. });
  47348. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47349. get: function () {
  47350. return Animation._ANIMATIONTYPE_COLOR3;
  47351. },
  47352. enumerable: true,
  47353. configurable: true
  47354. });
  47355. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47356. get: function () {
  47357. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47358. },
  47359. enumerable: true,
  47360. configurable: true
  47361. });
  47362. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47363. get: function () {
  47364. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47365. },
  47366. enumerable: true,
  47367. configurable: true
  47368. });
  47369. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47370. get: function () {
  47371. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47372. },
  47373. enumerable: true,
  47374. configurable: true
  47375. });
  47376. Animation.Parse = function (parsedAnimation) {
  47377. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47378. var dataType = parsedAnimation.dataType;
  47379. var keys = [];
  47380. var data;
  47381. var index;
  47382. if (parsedAnimation.enableBlending) {
  47383. animation.enableBlending = parsedAnimation.enableBlending;
  47384. }
  47385. if (parsedAnimation.blendingSpeed) {
  47386. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47387. }
  47388. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47389. var key = parsedAnimation.keys[index];
  47390. var inTangent;
  47391. var outTangent;
  47392. switch (dataType) {
  47393. case Animation.ANIMATIONTYPE_FLOAT:
  47394. data = key.values[0];
  47395. if (key.values.length >= 1) {
  47396. inTangent = key.values[1];
  47397. }
  47398. if (key.values.length >= 2) {
  47399. outTangent = key.values[2];
  47400. }
  47401. break;
  47402. case Animation.ANIMATIONTYPE_QUATERNION:
  47403. data = BABYLON.Quaternion.FromArray(key.values);
  47404. if (key.values.length >= 8) {
  47405. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47406. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47407. inTangent = _inTangent;
  47408. }
  47409. }
  47410. if (key.values.length >= 12) {
  47411. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47412. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47413. outTangent = _outTangent;
  47414. }
  47415. }
  47416. break;
  47417. case Animation.ANIMATIONTYPE_MATRIX:
  47418. data = BABYLON.Matrix.FromArray(key.values);
  47419. break;
  47420. case Animation.ANIMATIONTYPE_COLOR3:
  47421. data = BABYLON.Color3.FromArray(key.values);
  47422. break;
  47423. case Animation.ANIMATIONTYPE_VECTOR3:
  47424. default:
  47425. data = BABYLON.Vector3.FromArray(key.values);
  47426. break;
  47427. }
  47428. var keyData = {};
  47429. keyData.frame = key.frame;
  47430. keyData.value = data;
  47431. if (inTangent != undefined) {
  47432. keyData.inTangent = inTangent;
  47433. }
  47434. if (outTangent != undefined) {
  47435. keyData.outTangent = outTangent;
  47436. }
  47437. keys.push(keyData);
  47438. }
  47439. animation.setKeys(keys);
  47440. if (parsedAnimation.ranges) {
  47441. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47442. data = parsedAnimation.ranges[index];
  47443. animation.createRange(data.name, data.from, data.to);
  47444. }
  47445. }
  47446. return animation;
  47447. };
  47448. Animation.AppendSerializedAnimations = function (source, destination) {
  47449. if (source.animations) {
  47450. destination.animations = [];
  47451. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47452. var animation = source.animations[animationIndex];
  47453. destination.animations.push(animation.serialize());
  47454. }
  47455. }
  47456. };
  47457. Animation.AllowMatricesInterpolation = false;
  47458. // Statics
  47459. Animation._ANIMATIONTYPE_FLOAT = 0;
  47460. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47461. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47462. Animation._ANIMATIONTYPE_MATRIX = 3;
  47463. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47464. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47465. Animation._ANIMATIONTYPE_SIZE = 6;
  47466. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47467. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47468. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47469. return Animation;
  47470. }());
  47471. BABYLON.Animation = Animation;
  47472. })(BABYLON || (BABYLON = {}));
  47473. //# sourceMappingURL=babylon.animation.js.map
  47474. "use strict";
  47475. var BABYLON;
  47476. (function (BABYLON) {
  47477. /**
  47478. * This class defines the direct association between an animation and a target
  47479. */
  47480. var TargetedAnimation = /** @class */ (function () {
  47481. function TargetedAnimation() {
  47482. }
  47483. return TargetedAnimation;
  47484. }());
  47485. BABYLON.TargetedAnimation = TargetedAnimation;
  47486. /**
  47487. * Use this class to create coordinated animations on multiple targets
  47488. */
  47489. var AnimationGroup = /** @class */ (function () {
  47490. function AnimationGroup(name, scene) {
  47491. if (scene === void 0) { scene = null; }
  47492. this.name = name;
  47493. this._targetedAnimations = new Array();
  47494. this._animatables = new Array();
  47495. this._from = Number.MAX_VALUE;
  47496. this._to = -Number.MAX_VALUE;
  47497. this._speedRatio = 1;
  47498. this.onAnimationEndObservable = new BABYLON.Observable();
  47499. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47500. this._scene.animationGroups.push(this);
  47501. }
  47502. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47503. /**
  47504. * Define if the animations are started
  47505. */
  47506. get: function () {
  47507. return this._isStarted;
  47508. },
  47509. enumerable: true,
  47510. configurable: true
  47511. });
  47512. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47513. /**
  47514. * Gets or sets the speed ratio to use for all animations
  47515. */
  47516. get: function () {
  47517. return this._speedRatio;
  47518. },
  47519. /**
  47520. * Gets or sets the speed ratio to use for all animations
  47521. */
  47522. set: function (value) {
  47523. if (this._speedRatio === value) {
  47524. return;
  47525. }
  47526. this._speedRatio = value;
  47527. for (var index = 0; index < this._animatables.length; index++) {
  47528. var animatable = this._animatables[index];
  47529. animatable.speedRatio = this._speedRatio;
  47530. }
  47531. },
  47532. enumerable: true,
  47533. configurable: true
  47534. });
  47535. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47536. /**
  47537. * Gets the targeted animations for this animation group
  47538. */
  47539. get: function () {
  47540. return this._targetedAnimations;
  47541. },
  47542. enumerable: true,
  47543. configurable: true
  47544. });
  47545. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47546. /**
  47547. * returning the list of animatables controlled by this animation group.
  47548. */
  47549. get: function () {
  47550. return this._animatables;
  47551. },
  47552. enumerable: true,
  47553. configurable: true
  47554. });
  47555. /**
  47556. * Add an animation (with its target) in the group
  47557. * @param animation defines the animation we want to add
  47558. * @param target defines the target of the animation
  47559. * @returns the {BABYLON.TargetedAnimation} object
  47560. */
  47561. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47562. var targetedAnimation = {
  47563. animation: animation,
  47564. target: target
  47565. };
  47566. var keys = animation.getKeys();
  47567. if (this._from > keys[0].frame) {
  47568. this._from = keys[0].frame;
  47569. }
  47570. if (this._to < keys[keys.length - 1].frame) {
  47571. this._to = keys[keys.length - 1].frame;
  47572. }
  47573. this._targetedAnimations.push(targetedAnimation);
  47574. return targetedAnimation;
  47575. };
  47576. /**
  47577. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47578. * It can add constant keys at begin or end
  47579. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47580. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47581. */
  47582. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47583. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47584. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47585. beginFrame = Math.max(beginFrame, this._from);
  47586. endFrame = Math.min(endFrame, this._to);
  47587. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47588. var targetedAnimation = this._targetedAnimations[index];
  47589. var keys = targetedAnimation.animation.getKeys();
  47590. var startKey = keys[0];
  47591. var endKey = keys[keys.length - 1];
  47592. if (startKey.frame > beginFrame) {
  47593. var newKey = {
  47594. frame: beginFrame,
  47595. value: startKey.value,
  47596. inTangent: startKey.inTangent,
  47597. outTangent: startKey.outTangent,
  47598. interpolation: startKey.interpolation
  47599. };
  47600. keys.splice(0, 0, newKey);
  47601. }
  47602. if (endKey.frame < endFrame) {
  47603. var newKey = {
  47604. frame: endFrame,
  47605. value: endKey.value,
  47606. inTangent: endKey.outTangent,
  47607. outTangent: endKey.outTangent,
  47608. interpolation: endKey.interpolation
  47609. };
  47610. keys.push(newKey);
  47611. }
  47612. }
  47613. return this;
  47614. };
  47615. /**
  47616. * Start all animations on given targets
  47617. * @param loop defines if animations must loop
  47618. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47619. * @param from defines the from key (optional)
  47620. * @param to defines the to key (optional)
  47621. * @returns the current animation group
  47622. */
  47623. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47624. var _this = this;
  47625. if (loop === void 0) { loop = false; }
  47626. if (speedRatio === void 0) { speedRatio = 1; }
  47627. if (this._isStarted || this._targetedAnimations.length === 0) {
  47628. return this;
  47629. }
  47630. var _loop_1 = function () {
  47631. var targetedAnimation = this_1._targetedAnimations[index];
  47632. if (!targetedAnimation.target.animations) {
  47633. targetedAnimation.target.animations = [];
  47634. }
  47635. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47636. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47637. }
  47638. 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 () {
  47639. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47640. }));
  47641. };
  47642. var this_1 = this;
  47643. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47644. _loop_1();
  47645. }
  47646. this._speedRatio = speedRatio;
  47647. this._isStarted = true;
  47648. return this;
  47649. };
  47650. /**
  47651. * Pause all animations
  47652. */
  47653. AnimationGroup.prototype.pause = function () {
  47654. if (!this._isStarted) {
  47655. return this;
  47656. }
  47657. for (var index = 0; index < this._animatables.length; index++) {
  47658. var animatable = this._animatables[index];
  47659. animatable.pause();
  47660. }
  47661. return this;
  47662. };
  47663. /**
  47664. * Play all animations to initial state
  47665. * This function will start() the animations if they were not started or will restart() them if they were paused
  47666. * @param loop defines if animations must loop
  47667. */
  47668. AnimationGroup.prototype.play = function (loop) {
  47669. if (this.isStarted) {
  47670. if (loop !== undefined) {
  47671. for (var index = 0; index < this._animatables.length; index++) {
  47672. var animatable = this._animatables[index];
  47673. animatable.loopAnimation = loop;
  47674. }
  47675. }
  47676. this.restart();
  47677. }
  47678. else {
  47679. this.start(loop, this._speedRatio);
  47680. }
  47681. return this;
  47682. };
  47683. /**
  47684. * Reset all animations to initial state
  47685. */
  47686. AnimationGroup.prototype.reset = function () {
  47687. if (!this._isStarted) {
  47688. return this;
  47689. }
  47690. for (var index = 0; index < this._animatables.length; index++) {
  47691. var animatable = this._animatables[index];
  47692. animatable.reset();
  47693. }
  47694. return this;
  47695. };
  47696. /**
  47697. * Restart animations from key 0
  47698. */
  47699. AnimationGroup.prototype.restart = function () {
  47700. if (!this._isStarted) {
  47701. return this;
  47702. }
  47703. for (var index = 0; index < this._animatables.length; index++) {
  47704. var animatable = this._animatables[index];
  47705. animatable.restart();
  47706. }
  47707. return this;
  47708. };
  47709. /**
  47710. * Stop all animations
  47711. */
  47712. AnimationGroup.prototype.stop = function () {
  47713. if (!this._isStarted) {
  47714. return this;
  47715. }
  47716. for (var index = 0; index < this._animatables.length; index++) {
  47717. var animatable = this._animatables[index];
  47718. animatable.stop();
  47719. }
  47720. this._isStarted = false;
  47721. return this;
  47722. };
  47723. /**
  47724. * Goes to a specific frame in this animation group
  47725. *
  47726. * @param frame the frame number to go to
  47727. * @return the animationGroup
  47728. */
  47729. AnimationGroup.prototype.goToFrame = function (frame) {
  47730. if (!this._isStarted) {
  47731. return this;
  47732. }
  47733. for (var index = 0; index < this._animatables.length; index++) {
  47734. var animatable = this._animatables[index];
  47735. animatable.goToFrame(frame);
  47736. }
  47737. return this;
  47738. };
  47739. /**
  47740. * Dispose all associated resources
  47741. */
  47742. AnimationGroup.prototype.dispose = function () {
  47743. this._targetedAnimations = [];
  47744. this._animatables = [];
  47745. var index = this._scene.animationGroups.indexOf(this);
  47746. if (index > -1) {
  47747. this._scene.animationGroups.splice(index, 1);
  47748. }
  47749. };
  47750. return AnimationGroup;
  47751. }());
  47752. BABYLON.AnimationGroup = AnimationGroup;
  47753. })(BABYLON || (BABYLON = {}));
  47754. //# sourceMappingURL=babylon.animationGroup.js.map
  47755. "use strict";
  47756. var BABYLON;
  47757. (function (BABYLON) {
  47758. var RuntimeAnimation = /** @class */ (function () {
  47759. /**
  47760. * Create a new RuntimeAnimation object
  47761. * @param target defines the target of the animation
  47762. * @param animation defines the source {BABYLON.Animation} object
  47763. * @param scene defines the hosting scene
  47764. * @param host defines the initiating Animatable
  47765. */
  47766. function RuntimeAnimation(target, animation, scene, host) {
  47767. this._currentFrame = 0;
  47768. this._offsetsCache = {};
  47769. this._highLimitsCache = {};
  47770. this._stopped = false;
  47771. this._blendingFactor = 0;
  47772. this._targetPath = "";
  47773. this._weight = 1.0;
  47774. this._ratioOffset = 0;
  47775. this._previousDelay = 0;
  47776. this._previousRatio = 0;
  47777. this._animation = animation;
  47778. this._target = target;
  47779. this._scene = scene;
  47780. this._host = host;
  47781. animation._runtimeAnimations.push(this);
  47782. }
  47783. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47784. /**
  47785. * Gets the current frame
  47786. */
  47787. get: function () {
  47788. return this._currentFrame;
  47789. },
  47790. enumerable: true,
  47791. configurable: true
  47792. });
  47793. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47794. /**
  47795. * Gets the weight of the runtime animation
  47796. */
  47797. get: function () {
  47798. return this._weight;
  47799. },
  47800. enumerable: true,
  47801. configurable: true
  47802. });
  47803. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47804. /**
  47805. * Gets the original value of the runtime animation
  47806. */
  47807. get: function () {
  47808. return this._originalValue;
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47814. /**
  47815. * Gets the current value of the runtime animation
  47816. */
  47817. get: function () {
  47818. return this._currentValue;
  47819. },
  47820. enumerable: true,
  47821. configurable: true
  47822. });
  47823. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47824. /**
  47825. * Gets the path where to store the animated value in the target
  47826. */
  47827. get: function () {
  47828. return this._targetPath;
  47829. },
  47830. enumerable: true,
  47831. configurable: true
  47832. });
  47833. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47834. /**
  47835. * Gets the actual target of the runtime animation
  47836. */
  47837. get: function () {
  47838. return this._activeTarget;
  47839. },
  47840. enumerable: true,
  47841. configurable: true
  47842. });
  47843. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47844. get: function () {
  47845. return this._animation;
  47846. },
  47847. enumerable: true,
  47848. configurable: true
  47849. });
  47850. RuntimeAnimation.prototype.reset = function () {
  47851. this._offsetsCache = {};
  47852. this._highLimitsCache = {};
  47853. this._currentFrame = 0;
  47854. this._blendingFactor = 0;
  47855. this._originalValue = null;
  47856. };
  47857. RuntimeAnimation.prototype.isStopped = function () {
  47858. return this._stopped;
  47859. };
  47860. RuntimeAnimation.prototype.dispose = function () {
  47861. var index = this._animation.runtimeAnimations.indexOf(this);
  47862. if (index > -1) {
  47863. this._animation.runtimeAnimations.splice(index, 1);
  47864. }
  47865. };
  47866. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47867. if (typeof value === "function") {
  47868. return value();
  47869. }
  47870. return value;
  47871. };
  47872. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47873. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47874. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47875. }
  47876. this._currentFrame = currentFrame;
  47877. var keys = this._animation.getKeys();
  47878. // Try to get a hash to find the right key
  47879. 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));
  47880. if (keys[startKeyIndex].frame >= currentFrame) {
  47881. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47882. startKeyIndex--;
  47883. }
  47884. }
  47885. for (var key = startKeyIndex; key < keys.length; key++) {
  47886. var endKey = keys[key + 1];
  47887. if (endKey.frame >= currentFrame) {
  47888. var startKey = keys[key];
  47889. var startValue = this._getKeyValue(startKey.value);
  47890. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47891. return startValue;
  47892. }
  47893. var endValue = this._getKeyValue(endKey.value);
  47894. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47895. var frameDelta = endKey.frame - startKey.frame;
  47896. // gradient : percent of currentFrame between the frame inf and the frame sup
  47897. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47898. // check for easingFunction and correction of gradient
  47899. var easingFunction = this._animation.getEasingFunction();
  47900. if (easingFunction != null) {
  47901. gradient = easingFunction.ease(gradient);
  47902. }
  47903. switch (this._animation.dataType) {
  47904. // Float
  47905. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47906. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47907. switch (loopMode) {
  47908. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47909. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47910. return floatValue;
  47911. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47912. return offsetValue * repeatCount + floatValue;
  47913. }
  47914. break;
  47915. // Quaternion
  47916. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47917. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47918. switch (loopMode) {
  47919. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47920. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47921. return quatValue;
  47922. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47923. return quatValue.add(offsetValue.scale(repeatCount));
  47924. }
  47925. return quatValue;
  47926. // Vector3
  47927. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47928. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47929. switch (loopMode) {
  47930. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47931. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47932. return vec3Value;
  47933. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47934. return vec3Value.add(offsetValue.scale(repeatCount));
  47935. }
  47936. // Vector2
  47937. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47938. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47939. switch (loopMode) {
  47940. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47941. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47942. return vec2Value;
  47943. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47944. return vec2Value.add(offsetValue.scale(repeatCount));
  47945. }
  47946. // Size
  47947. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47948. switch (loopMode) {
  47949. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47950. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47951. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47952. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47953. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47954. }
  47955. // Color3
  47956. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47957. switch (loopMode) {
  47958. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47959. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47960. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47961. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47962. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47963. }
  47964. // Matrix
  47965. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47966. switch (loopMode) {
  47967. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47968. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47969. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47970. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47971. }
  47972. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47973. return startValue;
  47974. }
  47975. default:
  47976. break;
  47977. }
  47978. break;
  47979. }
  47980. }
  47981. return this._getKeyValue(keys[keys.length - 1].value);
  47982. };
  47983. /**
  47984. * Affect the interpolated value to the target
  47985. * @param currentValue defines the value computed by the animation
  47986. * @param weight defines the weight to apply to this value
  47987. */
  47988. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47989. if (weight === void 0) { weight = 1.0; }
  47990. // Set value
  47991. var path;
  47992. var destination;
  47993. var targetPropertyPath = this._animation.targetPropertyPath;
  47994. if (targetPropertyPath.length > 1) {
  47995. var property = this._target[targetPropertyPath[0]];
  47996. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47997. property = property[targetPropertyPath[index]];
  47998. }
  47999. path = targetPropertyPath[targetPropertyPath.length - 1];
  48000. destination = property;
  48001. }
  48002. else {
  48003. path = targetPropertyPath[0];
  48004. destination = this._target;
  48005. }
  48006. this._targetPath = path;
  48007. this._activeTarget = destination;
  48008. this._weight = weight;
  48009. // Blending
  48010. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  48011. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  48012. if (enableBlending && this._blendingFactor <= 1.0) {
  48013. if (!this._originalBlendValue) {
  48014. var originalValue = destination[path];
  48015. if (originalValue.clone) {
  48016. this._originalBlendValue = originalValue.clone();
  48017. }
  48018. else {
  48019. this._originalBlendValue = originalValue;
  48020. }
  48021. }
  48022. }
  48023. if (weight !== -1.0) {
  48024. if (!this._originalValue) {
  48025. var originalValue = void 0;
  48026. if (destination.getRestPose) {
  48027. originalValue = destination.getRestPose();
  48028. }
  48029. else {
  48030. originalValue = destination[path];
  48031. }
  48032. if (originalValue.clone) {
  48033. this._originalValue = originalValue.clone();
  48034. }
  48035. else {
  48036. this._originalValue = originalValue;
  48037. }
  48038. }
  48039. }
  48040. if (enableBlending && this._blendingFactor <= 1.0) {
  48041. if (this._originalBlendValue.prototype) {
  48042. if (this._originalBlendValue.prototype.Lerp) {
  48043. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48044. }
  48045. else {
  48046. this._currentValue = currentValue;
  48047. }
  48048. }
  48049. else if (this._originalBlendValue.m) {
  48050. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48051. }
  48052. else {
  48053. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48054. }
  48055. this._blendingFactor += blendingSpeed;
  48056. }
  48057. else {
  48058. this._currentValue = currentValue;
  48059. }
  48060. if (weight !== -1.0) {
  48061. this._scene._registerTargetForLateAnimationBinding(this);
  48062. }
  48063. else {
  48064. destination[path] = this._currentValue;
  48065. }
  48066. if (this._target.markAsDirty) {
  48067. this._target.markAsDirty(this._animation.targetProperty);
  48068. }
  48069. };
  48070. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48071. if (this._target && this._target.animationPropertiesOverride) {
  48072. return this._target.animationPropertiesOverride.loopMode;
  48073. }
  48074. return this._animation.loopMode;
  48075. };
  48076. /**
  48077. * Move the current animation to a given frame
  48078. * @param frame defines the frame to move to
  48079. */
  48080. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48081. var keys = this._animation.getKeys();
  48082. if (frame < keys[0].frame) {
  48083. frame = keys[0].frame;
  48084. }
  48085. else if (frame > keys[keys.length - 1].frame) {
  48086. frame = keys[keys.length - 1].frame;
  48087. }
  48088. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48089. this.setValue(currentValue, -1);
  48090. };
  48091. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48092. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48093. this._ratioOffset = this._previousRatio - newRatio;
  48094. };
  48095. /**
  48096. * Execute the current animation
  48097. * @param delay defines the delay to add to the current frame
  48098. * @param from defines the lower bound of the animation range
  48099. * @param to defines the upper bound of the animation range
  48100. * @param loop defines if the current animation must loop
  48101. * @param speedRatio defines the current speed ratio
  48102. * @param weight defines the weight of the animation (default is -1 so no weight)
  48103. * @returns a boolean indicating if the animation has ended
  48104. */
  48105. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48106. if (weight === void 0) { weight = -1.0; }
  48107. var targetPropertyPath = this._animation.targetPropertyPath;
  48108. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48109. this._stopped = true;
  48110. return false;
  48111. }
  48112. var returnValue = true;
  48113. var keys = this._animation.getKeys();
  48114. // Adding a start key at frame 0 if missing
  48115. if (keys[0].frame !== 0) {
  48116. var newKey = { frame: 0, value: keys[0].value };
  48117. keys.splice(0, 0, newKey);
  48118. }
  48119. // Check limits
  48120. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48121. from = keys[0].frame;
  48122. }
  48123. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48124. to = keys[keys.length - 1].frame;
  48125. }
  48126. //to and from cannot be the same key
  48127. if (from === to) {
  48128. if (from > keys[0].frame) {
  48129. from--;
  48130. }
  48131. else if (to < keys[keys.length - 1].frame) {
  48132. to++;
  48133. }
  48134. }
  48135. // Compute ratio
  48136. var range = to - from;
  48137. var offsetValue;
  48138. // ratio represents the frame delta between from and to
  48139. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48140. var highLimitValue = 0;
  48141. this._previousDelay = delay;
  48142. this._previousRatio = ratio;
  48143. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48144. returnValue = false;
  48145. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48146. }
  48147. else {
  48148. // Get max value if required
  48149. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48150. var keyOffset = to.toString() + from.toString();
  48151. if (!this._offsetsCache[keyOffset]) {
  48152. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48153. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48154. switch (this._animation.dataType) {
  48155. // Float
  48156. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48157. this._offsetsCache[keyOffset] = toValue - fromValue;
  48158. break;
  48159. // Quaternion
  48160. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48161. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48162. break;
  48163. // Vector3
  48164. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48165. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48166. // Vector2
  48167. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48168. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48169. // Size
  48170. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48171. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48172. // Color3
  48173. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48174. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48175. default:
  48176. break;
  48177. }
  48178. this._highLimitsCache[keyOffset] = toValue;
  48179. }
  48180. highLimitValue = this._highLimitsCache[keyOffset];
  48181. offsetValue = this._offsetsCache[keyOffset];
  48182. }
  48183. }
  48184. if (offsetValue === undefined) {
  48185. switch (this._animation.dataType) {
  48186. // Float
  48187. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48188. offsetValue = 0;
  48189. break;
  48190. // Quaternion
  48191. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48192. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48193. break;
  48194. // Vector3
  48195. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48196. offsetValue = BABYLON.Vector3.Zero();
  48197. break;
  48198. // Vector2
  48199. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48200. offsetValue = BABYLON.Vector2.Zero();
  48201. break;
  48202. // Size
  48203. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48204. offsetValue = BABYLON.Size.Zero();
  48205. break;
  48206. // Color3
  48207. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48208. offsetValue = BABYLON.Color3.Black();
  48209. }
  48210. }
  48211. // Compute value
  48212. var repeatCount = (ratio / range) >> 0;
  48213. var currentFrame = returnValue ? from + ratio % range : to;
  48214. // Need to normalize?
  48215. if (this._host && this._host.syncRoot) {
  48216. var syncRoot = this._host.syncRoot;
  48217. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48218. currentFrame = from + (to - from) * hostNormalizedFrame;
  48219. }
  48220. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48221. // Set value
  48222. this.setValue(currentValue, weight);
  48223. // Check events
  48224. var events = this._animation.getEvents();
  48225. for (var index = 0; index < events.length; index++) {
  48226. // Make sure current frame has passed event frame and that event frame is within the current range
  48227. // Also, handle both forward and reverse animations
  48228. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48229. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48230. var event = events[index];
  48231. if (!event.isDone) {
  48232. // If event should be done only once, remove it.
  48233. if (event.onlyOnce) {
  48234. events.splice(index, 1);
  48235. index--;
  48236. }
  48237. event.isDone = true;
  48238. event.action();
  48239. } // Don't do anything if the event has already be done.
  48240. }
  48241. else if (events[index].isDone && !events[index].onlyOnce) {
  48242. // reset event, the animation is looping
  48243. events[index].isDone = false;
  48244. }
  48245. }
  48246. if (!returnValue) {
  48247. this._stopped = true;
  48248. }
  48249. return returnValue;
  48250. };
  48251. return RuntimeAnimation;
  48252. }());
  48253. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48254. })(BABYLON || (BABYLON = {}));
  48255. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48256. "use strict";
  48257. var BABYLON;
  48258. (function (BABYLON) {
  48259. var Animatable = /** @class */ (function () {
  48260. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48261. if (fromFrame === void 0) { fromFrame = 0; }
  48262. if (toFrame === void 0) { toFrame = 100; }
  48263. if (loopAnimation === void 0) { loopAnimation = false; }
  48264. if (speedRatio === void 0) { speedRatio = 1.0; }
  48265. this.target = target;
  48266. this.fromFrame = fromFrame;
  48267. this.toFrame = toFrame;
  48268. this.loopAnimation = loopAnimation;
  48269. this.onAnimationEnd = onAnimationEnd;
  48270. this._localDelayOffset = null;
  48271. this._pausedDelay = null;
  48272. this._runtimeAnimations = new Array();
  48273. this._paused = false;
  48274. this._speedRatio = 1;
  48275. this._weight = -1.0;
  48276. this.animationStarted = false;
  48277. if (animations) {
  48278. this.appendAnimations(target, animations);
  48279. }
  48280. this._speedRatio = speedRatio;
  48281. this._scene = scene;
  48282. scene._activeAnimatables.push(this);
  48283. }
  48284. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48285. /**
  48286. * Gets the root Animatable used to synchronize and normalize animations
  48287. */
  48288. get: function () {
  48289. return this._syncRoot;
  48290. },
  48291. enumerable: true,
  48292. configurable: true
  48293. });
  48294. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48295. /**
  48296. * Gets the current frame of the first RuntimeAnimation
  48297. * Used to synchronize Animatables
  48298. */
  48299. get: function () {
  48300. if (this._runtimeAnimations.length === 0) {
  48301. return 0;
  48302. }
  48303. return this._runtimeAnimations[0].currentFrame;
  48304. },
  48305. enumerable: true,
  48306. configurable: true
  48307. });
  48308. Object.defineProperty(Animatable.prototype, "weight", {
  48309. /**
  48310. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48311. */
  48312. get: function () {
  48313. return this._weight;
  48314. },
  48315. set: function (value) {
  48316. if (value === -1) {
  48317. this._weight = -1;
  48318. return;
  48319. }
  48320. // Else weight must be in [0, 1] range
  48321. this._weight = Math.min(Math.max(value, 0), 1.0);
  48322. },
  48323. enumerable: true,
  48324. configurable: true
  48325. });
  48326. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48327. /**
  48328. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48329. */
  48330. get: function () {
  48331. return this._speedRatio;
  48332. },
  48333. set: function (value) {
  48334. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48335. var animation = this._runtimeAnimations[index];
  48336. animation._prepareForSpeedRatioChange(value);
  48337. }
  48338. this._speedRatio = value;
  48339. },
  48340. enumerable: true,
  48341. configurable: true
  48342. });
  48343. // Methods
  48344. /**
  48345. * Synchronize and normalize current Animatable with a source Animatable.
  48346. * This is useful when using animation weights and when animations are not of the same length
  48347. * @param root defines the root Animatable to synchronize with
  48348. * @returns the current Animatable
  48349. */
  48350. Animatable.prototype.syncWith = function (root) {
  48351. this._syncRoot = root;
  48352. if (root) {
  48353. // Make sure this animatable will animate after the root
  48354. var index = this._scene._activeAnimatables.indexOf(this);
  48355. if (index > -1) {
  48356. this._scene._activeAnimatables.splice(index, 1);
  48357. this._scene._activeAnimatables.push(this);
  48358. }
  48359. }
  48360. return this;
  48361. };
  48362. Animatable.prototype.getAnimations = function () {
  48363. return this._runtimeAnimations;
  48364. };
  48365. Animatable.prototype.appendAnimations = function (target, animations) {
  48366. for (var index = 0; index < animations.length; index++) {
  48367. var animation = animations[index];
  48368. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48369. }
  48370. };
  48371. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48372. var runtimeAnimations = this._runtimeAnimations;
  48373. for (var index = 0; index < runtimeAnimations.length; index++) {
  48374. if (runtimeAnimations[index].animation.targetProperty === property) {
  48375. return runtimeAnimations[index].animation;
  48376. }
  48377. }
  48378. return null;
  48379. };
  48380. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48381. var runtimeAnimations = this._runtimeAnimations;
  48382. for (var index = 0; index < runtimeAnimations.length; index++) {
  48383. if (runtimeAnimations[index].animation.targetProperty === property) {
  48384. return runtimeAnimations[index];
  48385. }
  48386. }
  48387. return null;
  48388. };
  48389. Animatable.prototype.reset = function () {
  48390. var runtimeAnimations = this._runtimeAnimations;
  48391. for (var index = 0; index < runtimeAnimations.length; index++) {
  48392. runtimeAnimations[index].reset();
  48393. }
  48394. // Reset to original value
  48395. for (index = 0; index < runtimeAnimations.length; index++) {
  48396. var animation = runtimeAnimations[index];
  48397. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48398. }
  48399. this._localDelayOffset = null;
  48400. this._pausedDelay = null;
  48401. };
  48402. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48403. var runtimeAnimations = this._runtimeAnimations;
  48404. for (var index = 0; index < runtimeAnimations.length; index++) {
  48405. runtimeAnimations[index].animation.enableBlending = true;
  48406. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48407. }
  48408. };
  48409. Animatable.prototype.disableBlending = function () {
  48410. var runtimeAnimations = this._runtimeAnimations;
  48411. for (var index = 0; index < runtimeAnimations.length; index++) {
  48412. runtimeAnimations[index].animation.enableBlending = false;
  48413. }
  48414. };
  48415. Animatable.prototype.goToFrame = function (frame) {
  48416. var runtimeAnimations = this._runtimeAnimations;
  48417. if (runtimeAnimations[0]) {
  48418. var fps = runtimeAnimations[0].animation.framePerSecond;
  48419. var currentFrame = runtimeAnimations[0].currentFrame;
  48420. var adjustTime = frame - currentFrame;
  48421. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48422. if (this._localDelayOffset === null) {
  48423. this._localDelayOffset = 0;
  48424. }
  48425. this._localDelayOffset -= delay;
  48426. }
  48427. for (var index = 0; index < runtimeAnimations.length; index++) {
  48428. runtimeAnimations[index].goToFrame(frame);
  48429. }
  48430. };
  48431. Animatable.prototype.pause = function () {
  48432. if (this._paused) {
  48433. return;
  48434. }
  48435. this._paused = true;
  48436. };
  48437. Animatable.prototype.restart = function () {
  48438. this._paused = false;
  48439. };
  48440. Animatable.prototype.stop = function (animationName) {
  48441. if (animationName) {
  48442. var idx = this._scene._activeAnimatables.indexOf(this);
  48443. if (idx > -1) {
  48444. var runtimeAnimations = this._runtimeAnimations;
  48445. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48446. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48447. continue;
  48448. }
  48449. runtimeAnimations[index].dispose();
  48450. runtimeAnimations.splice(index, 1);
  48451. }
  48452. if (runtimeAnimations.length == 0) {
  48453. this._scene._activeAnimatables.splice(idx, 1);
  48454. if (this.onAnimationEnd) {
  48455. this.onAnimationEnd();
  48456. }
  48457. }
  48458. }
  48459. }
  48460. else {
  48461. var index = this._scene._activeAnimatables.indexOf(this);
  48462. if (index > -1) {
  48463. this._scene._activeAnimatables.splice(index, 1);
  48464. var runtimeAnimations = this._runtimeAnimations;
  48465. for (var index = 0; index < runtimeAnimations.length; index++) {
  48466. runtimeAnimations[index].dispose();
  48467. }
  48468. if (this.onAnimationEnd) {
  48469. this.onAnimationEnd();
  48470. }
  48471. }
  48472. }
  48473. };
  48474. Animatable.prototype._animate = function (delay) {
  48475. if (this._paused) {
  48476. this.animationStarted = false;
  48477. if (this._pausedDelay === null) {
  48478. this._pausedDelay = delay;
  48479. }
  48480. return true;
  48481. }
  48482. if (this._localDelayOffset === null) {
  48483. this._localDelayOffset = delay;
  48484. this._pausedDelay = null;
  48485. }
  48486. else if (this._pausedDelay !== null) {
  48487. this._localDelayOffset += delay - this._pausedDelay;
  48488. this._pausedDelay = null;
  48489. }
  48490. if (this._weight === 0) {
  48491. return true;
  48492. }
  48493. // Animating
  48494. var running = false;
  48495. var runtimeAnimations = this._runtimeAnimations;
  48496. var index;
  48497. for (index = 0; index < runtimeAnimations.length; index++) {
  48498. var animation = runtimeAnimations[index];
  48499. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48500. running = running || isRunning;
  48501. }
  48502. this.animationStarted = running;
  48503. if (!running) {
  48504. // Remove from active animatables
  48505. index = this._scene._activeAnimatables.indexOf(this);
  48506. this._scene._activeAnimatables.splice(index, 1);
  48507. // Dispose all runtime animations
  48508. for (index = 0; index < runtimeAnimations.length; index++) {
  48509. runtimeAnimations[index].dispose();
  48510. }
  48511. }
  48512. if (!running && this.onAnimationEnd) {
  48513. this.onAnimationEnd();
  48514. this.onAnimationEnd = null;
  48515. }
  48516. return running;
  48517. };
  48518. return Animatable;
  48519. }());
  48520. BABYLON.Animatable = Animatable;
  48521. })(BABYLON || (BABYLON = {}));
  48522. //# sourceMappingURL=babylon.animatable.js.map
  48523. "use strict";
  48524. var BABYLON;
  48525. (function (BABYLON) {
  48526. var EasingFunction = /** @class */ (function () {
  48527. function EasingFunction() {
  48528. // Properties
  48529. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48530. }
  48531. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48532. get: function () {
  48533. return EasingFunction._EASINGMODE_EASEIN;
  48534. },
  48535. enumerable: true,
  48536. configurable: true
  48537. });
  48538. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48539. get: function () {
  48540. return EasingFunction._EASINGMODE_EASEOUT;
  48541. },
  48542. enumerable: true,
  48543. configurable: true
  48544. });
  48545. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48546. get: function () {
  48547. return EasingFunction._EASINGMODE_EASEINOUT;
  48548. },
  48549. enumerable: true,
  48550. configurable: true
  48551. });
  48552. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48553. var n = Math.min(Math.max(easingMode, 0), 2);
  48554. this._easingMode = n;
  48555. };
  48556. EasingFunction.prototype.getEasingMode = function () {
  48557. return this._easingMode;
  48558. };
  48559. EasingFunction.prototype.easeInCore = function (gradient) {
  48560. throw new Error('You must implement this method');
  48561. };
  48562. EasingFunction.prototype.ease = function (gradient) {
  48563. switch (this._easingMode) {
  48564. case EasingFunction.EASINGMODE_EASEIN:
  48565. return this.easeInCore(gradient);
  48566. case EasingFunction.EASINGMODE_EASEOUT:
  48567. return (1 - this.easeInCore(1 - gradient));
  48568. }
  48569. if (gradient >= 0.5) {
  48570. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48571. }
  48572. return (this.easeInCore(gradient * 2) * 0.5);
  48573. };
  48574. //Statics
  48575. EasingFunction._EASINGMODE_EASEIN = 0;
  48576. EasingFunction._EASINGMODE_EASEOUT = 1;
  48577. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48578. return EasingFunction;
  48579. }());
  48580. BABYLON.EasingFunction = EasingFunction;
  48581. var CircleEase = /** @class */ (function (_super) {
  48582. __extends(CircleEase, _super);
  48583. function CircleEase() {
  48584. return _super !== null && _super.apply(this, arguments) || this;
  48585. }
  48586. CircleEase.prototype.easeInCore = function (gradient) {
  48587. gradient = Math.max(0, Math.min(1, gradient));
  48588. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48589. };
  48590. return CircleEase;
  48591. }(EasingFunction));
  48592. BABYLON.CircleEase = CircleEase;
  48593. var BackEase = /** @class */ (function (_super) {
  48594. __extends(BackEase, _super);
  48595. function BackEase(amplitude) {
  48596. if (amplitude === void 0) { amplitude = 1; }
  48597. var _this = _super.call(this) || this;
  48598. _this.amplitude = amplitude;
  48599. return _this;
  48600. }
  48601. BackEase.prototype.easeInCore = function (gradient) {
  48602. var num = Math.max(0, this.amplitude);
  48603. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48604. };
  48605. return BackEase;
  48606. }(EasingFunction));
  48607. BABYLON.BackEase = BackEase;
  48608. var BounceEase = /** @class */ (function (_super) {
  48609. __extends(BounceEase, _super);
  48610. function BounceEase(bounces, bounciness) {
  48611. if (bounces === void 0) { bounces = 3; }
  48612. if (bounciness === void 0) { bounciness = 2; }
  48613. var _this = _super.call(this) || this;
  48614. _this.bounces = bounces;
  48615. _this.bounciness = bounciness;
  48616. return _this;
  48617. }
  48618. BounceEase.prototype.easeInCore = function (gradient) {
  48619. var y = Math.max(0.0, this.bounces);
  48620. var bounciness = this.bounciness;
  48621. if (bounciness <= 1.0) {
  48622. bounciness = 1.001;
  48623. }
  48624. var num9 = Math.pow(bounciness, y);
  48625. var num5 = 1.0 - bounciness;
  48626. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48627. var num15 = gradient * num4;
  48628. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48629. var num3 = Math.floor(num65);
  48630. var num13 = num3 + 1.0;
  48631. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48632. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48633. var num7 = (num8 + num12) * 0.5;
  48634. var num6 = gradient - num7;
  48635. var num2 = num7 - num8;
  48636. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48637. };
  48638. return BounceEase;
  48639. }(EasingFunction));
  48640. BABYLON.BounceEase = BounceEase;
  48641. var CubicEase = /** @class */ (function (_super) {
  48642. __extends(CubicEase, _super);
  48643. function CubicEase() {
  48644. return _super !== null && _super.apply(this, arguments) || this;
  48645. }
  48646. CubicEase.prototype.easeInCore = function (gradient) {
  48647. return (gradient * gradient * gradient);
  48648. };
  48649. return CubicEase;
  48650. }(EasingFunction));
  48651. BABYLON.CubicEase = CubicEase;
  48652. var ElasticEase = /** @class */ (function (_super) {
  48653. __extends(ElasticEase, _super);
  48654. function ElasticEase(oscillations, springiness) {
  48655. if (oscillations === void 0) { oscillations = 3; }
  48656. if (springiness === void 0) { springiness = 3; }
  48657. var _this = _super.call(this) || this;
  48658. _this.oscillations = oscillations;
  48659. _this.springiness = springiness;
  48660. return _this;
  48661. }
  48662. ElasticEase.prototype.easeInCore = function (gradient) {
  48663. var num2;
  48664. var num3 = Math.max(0.0, this.oscillations);
  48665. var num = Math.max(0.0, this.springiness);
  48666. if (num == 0) {
  48667. num2 = gradient;
  48668. }
  48669. else {
  48670. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48671. }
  48672. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48673. };
  48674. return ElasticEase;
  48675. }(EasingFunction));
  48676. BABYLON.ElasticEase = ElasticEase;
  48677. var ExponentialEase = /** @class */ (function (_super) {
  48678. __extends(ExponentialEase, _super);
  48679. function ExponentialEase(exponent) {
  48680. if (exponent === void 0) { exponent = 2; }
  48681. var _this = _super.call(this) || this;
  48682. _this.exponent = exponent;
  48683. return _this;
  48684. }
  48685. ExponentialEase.prototype.easeInCore = function (gradient) {
  48686. if (this.exponent <= 0) {
  48687. return gradient;
  48688. }
  48689. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48690. };
  48691. return ExponentialEase;
  48692. }(EasingFunction));
  48693. BABYLON.ExponentialEase = ExponentialEase;
  48694. var PowerEase = /** @class */ (function (_super) {
  48695. __extends(PowerEase, _super);
  48696. function PowerEase(power) {
  48697. if (power === void 0) { power = 2; }
  48698. var _this = _super.call(this) || this;
  48699. _this.power = power;
  48700. return _this;
  48701. }
  48702. PowerEase.prototype.easeInCore = function (gradient) {
  48703. var y = Math.max(0.0, this.power);
  48704. return Math.pow(gradient, y);
  48705. };
  48706. return PowerEase;
  48707. }(EasingFunction));
  48708. BABYLON.PowerEase = PowerEase;
  48709. var QuadraticEase = /** @class */ (function (_super) {
  48710. __extends(QuadraticEase, _super);
  48711. function QuadraticEase() {
  48712. return _super !== null && _super.apply(this, arguments) || this;
  48713. }
  48714. QuadraticEase.prototype.easeInCore = function (gradient) {
  48715. return (gradient * gradient);
  48716. };
  48717. return QuadraticEase;
  48718. }(EasingFunction));
  48719. BABYLON.QuadraticEase = QuadraticEase;
  48720. var QuarticEase = /** @class */ (function (_super) {
  48721. __extends(QuarticEase, _super);
  48722. function QuarticEase() {
  48723. return _super !== null && _super.apply(this, arguments) || this;
  48724. }
  48725. QuarticEase.prototype.easeInCore = function (gradient) {
  48726. return (gradient * gradient * gradient * gradient);
  48727. };
  48728. return QuarticEase;
  48729. }(EasingFunction));
  48730. BABYLON.QuarticEase = QuarticEase;
  48731. var QuinticEase = /** @class */ (function (_super) {
  48732. __extends(QuinticEase, _super);
  48733. function QuinticEase() {
  48734. return _super !== null && _super.apply(this, arguments) || this;
  48735. }
  48736. QuinticEase.prototype.easeInCore = function (gradient) {
  48737. return (gradient * gradient * gradient * gradient * gradient);
  48738. };
  48739. return QuinticEase;
  48740. }(EasingFunction));
  48741. BABYLON.QuinticEase = QuinticEase;
  48742. var SineEase = /** @class */ (function (_super) {
  48743. __extends(SineEase, _super);
  48744. function SineEase() {
  48745. return _super !== null && _super.apply(this, arguments) || this;
  48746. }
  48747. SineEase.prototype.easeInCore = function (gradient) {
  48748. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48749. };
  48750. return SineEase;
  48751. }(EasingFunction));
  48752. BABYLON.SineEase = SineEase;
  48753. var BezierCurveEase = /** @class */ (function (_super) {
  48754. __extends(BezierCurveEase, _super);
  48755. function BezierCurveEase(x1, y1, x2, y2) {
  48756. if (x1 === void 0) { x1 = 0; }
  48757. if (y1 === void 0) { y1 = 0; }
  48758. if (x2 === void 0) { x2 = 1; }
  48759. if (y2 === void 0) { y2 = 1; }
  48760. var _this = _super.call(this) || this;
  48761. _this.x1 = x1;
  48762. _this.y1 = y1;
  48763. _this.x2 = x2;
  48764. _this.y2 = y2;
  48765. return _this;
  48766. }
  48767. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48768. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48769. };
  48770. return BezierCurveEase;
  48771. }(EasingFunction));
  48772. BABYLON.BezierCurveEase = BezierCurveEase;
  48773. })(BABYLON || (BABYLON = {}));
  48774. //# sourceMappingURL=babylon.easing.js.map
  48775. "use strict";
  48776. var BABYLON;
  48777. (function (BABYLON) {
  48778. /**
  48779. * A Condition applied to an Action
  48780. */
  48781. var Condition = /** @class */ (function () {
  48782. /**
  48783. * Creates a new Condition
  48784. * @param actionManager the manager of the action the condition is applied to
  48785. */
  48786. function Condition(actionManager) {
  48787. this._actionManager = actionManager;
  48788. }
  48789. /**
  48790. * Check if the current condition is valid
  48791. * @returns a boolean
  48792. */
  48793. Condition.prototype.isValid = function () {
  48794. return true;
  48795. };
  48796. /**
  48797. * Internal only
  48798. * @ignore
  48799. */
  48800. Condition.prototype._getProperty = function (propertyPath) {
  48801. return this._actionManager._getProperty(propertyPath);
  48802. };
  48803. /**
  48804. * Internal only
  48805. * @ignore
  48806. */
  48807. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48808. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48809. };
  48810. /**
  48811. * Serialize placeholder for child classes
  48812. * @returns the serialized object
  48813. */
  48814. Condition.prototype.serialize = function () {
  48815. };
  48816. /**
  48817. * Internal only
  48818. * @ignore
  48819. */
  48820. Condition.prototype._serialize = function (serializedCondition) {
  48821. return {
  48822. type: 2,
  48823. children: [],
  48824. name: serializedCondition.name,
  48825. properties: serializedCondition.properties
  48826. };
  48827. };
  48828. return Condition;
  48829. }());
  48830. BABYLON.Condition = Condition;
  48831. /**
  48832. * Defines specific conditional operators as extensions of Condition
  48833. */
  48834. var ValueCondition = /** @class */ (function (_super) {
  48835. __extends(ValueCondition, _super);
  48836. /**
  48837. * Creates a new ValueCondition
  48838. * @param actionManager manager for the action the condition applies to
  48839. * @param target for the action
  48840. * @param propertyPath path to specify the property of the target the conditional operator uses
  48841. * @param value the vale compared by the conditional operator against the current value of the property
  48842. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48843. */
  48844. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48845. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48846. var _this = _super.call(this, actionManager) || this;
  48847. _this.propertyPath = propertyPath;
  48848. _this.value = value;
  48849. _this.operator = operator;
  48850. _this._target = target;
  48851. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48852. _this._property = _this._getProperty(_this.propertyPath);
  48853. return _this;
  48854. }
  48855. Object.defineProperty(ValueCondition, "IsEqual", {
  48856. /**
  48857. * returns the number for IsEqual
  48858. */
  48859. get: function () {
  48860. return ValueCondition._IsEqual;
  48861. },
  48862. enumerable: true,
  48863. configurable: true
  48864. });
  48865. Object.defineProperty(ValueCondition, "IsDifferent", {
  48866. /**
  48867. * Returns the number for IsDifferent
  48868. */
  48869. get: function () {
  48870. return ValueCondition._IsDifferent;
  48871. },
  48872. enumerable: true,
  48873. configurable: true
  48874. });
  48875. Object.defineProperty(ValueCondition, "IsGreater", {
  48876. /**
  48877. * Returns the number for IsGreater
  48878. */
  48879. get: function () {
  48880. return ValueCondition._IsGreater;
  48881. },
  48882. enumerable: true,
  48883. configurable: true
  48884. });
  48885. Object.defineProperty(ValueCondition, "IsLesser", {
  48886. /**
  48887. * Returns the number for IsLesser
  48888. */
  48889. get: function () {
  48890. return ValueCondition._IsLesser;
  48891. },
  48892. enumerable: true,
  48893. configurable: true
  48894. });
  48895. /**
  48896. * Compares the given value with the property value for the specified conditional operator
  48897. * @returns the result of the comparison
  48898. */
  48899. ValueCondition.prototype.isValid = function () {
  48900. switch (this.operator) {
  48901. case ValueCondition.IsGreater:
  48902. return this._effectiveTarget[this._property] > this.value;
  48903. case ValueCondition.IsLesser:
  48904. return this._effectiveTarget[this._property] < this.value;
  48905. case ValueCondition.IsEqual:
  48906. case ValueCondition.IsDifferent:
  48907. var check;
  48908. if (this.value.equals) {
  48909. check = this.value.equals(this._effectiveTarget[this._property]);
  48910. }
  48911. else {
  48912. check = this.value === this._effectiveTarget[this._property];
  48913. }
  48914. return this.operator === ValueCondition.IsEqual ? check : !check;
  48915. }
  48916. return false;
  48917. };
  48918. /**
  48919. * Serialize the ValueCondition into a JSON compatible object
  48920. * @returns serialization object
  48921. */
  48922. ValueCondition.prototype.serialize = function () {
  48923. return this._serialize({
  48924. name: "ValueCondition",
  48925. properties: [
  48926. BABYLON.Action._GetTargetProperty(this._target),
  48927. { name: "propertyPath", value: this.propertyPath },
  48928. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48929. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48930. ]
  48931. });
  48932. };
  48933. /**
  48934. * Gets the name of the conditional operator for the ValueCondition
  48935. * @param operator the conditional operator
  48936. * @returns the name
  48937. */
  48938. ValueCondition.GetOperatorName = function (operator) {
  48939. switch (operator) {
  48940. case ValueCondition._IsEqual: return "IsEqual";
  48941. case ValueCondition._IsDifferent: return "IsDifferent";
  48942. case ValueCondition._IsGreater: return "IsGreater";
  48943. case ValueCondition._IsLesser: return "IsLesser";
  48944. default: return "";
  48945. }
  48946. };
  48947. /**
  48948. * Internal only
  48949. * @ignore
  48950. */
  48951. ValueCondition._IsEqual = 0;
  48952. /**
  48953. * Internal only
  48954. * @ignore
  48955. */
  48956. ValueCondition._IsDifferent = 1;
  48957. /**
  48958. * Internal only
  48959. * @ignore
  48960. */
  48961. ValueCondition._IsGreater = 2;
  48962. /**
  48963. * Internal only
  48964. * @ignore
  48965. */
  48966. ValueCondition._IsLesser = 3;
  48967. return ValueCondition;
  48968. }(Condition));
  48969. BABYLON.ValueCondition = ValueCondition;
  48970. /**
  48971. * Defines a predicate condition as an extension of Condition
  48972. */
  48973. var PredicateCondition = /** @class */ (function (_super) {
  48974. __extends(PredicateCondition, _super);
  48975. /**
  48976. * Creates a new {BABYLON.PredicateCondition}
  48977. * @param actionManager manager for the action the condition applies to
  48978. * @param predicate
  48979. */
  48980. function PredicateCondition(actionManager, predicate) {
  48981. var _this = _super.call(this, actionManager) || this;
  48982. _this.predicate = predicate;
  48983. return _this;
  48984. }
  48985. /**
  48986. * @returns the validity of the predicate condition
  48987. */
  48988. PredicateCondition.prototype.isValid = function () {
  48989. return this.predicate();
  48990. };
  48991. return PredicateCondition;
  48992. }(Condition));
  48993. BABYLON.PredicateCondition = PredicateCondition;
  48994. /**
  48995. * Defines a state condition as an extension of {BABYLON.Condition}
  48996. */
  48997. var StateCondition = /** @class */ (function (_super) {
  48998. __extends(StateCondition, _super);
  48999. /**
  49000. * Creates a new {BABYLON.StateCondition}
  49001. * @param actionManager manager for the action the condition applies to
  49002. * @param target of the condition
  49003. * @param value to compare with target state
  49004. */
  49005. function StateCondition(actionManager, target, value) {
  49006. var _this = _super.call(this, actionManager) || this;
  49007. _this.value = value;
  49008. _this._target = target;
  49009. return _this;
  49010. }
  49011. /**
  49012. * @returns the validity of the state
  49013. */
  49014. StateCondition.prototype.isValid = function () {
  49015. return this._target.state === this.value;
  49016. };
  49017. /**
  49018. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  49019. * @returns serialization object
  49020. */
  49021. StateCondition.prototype.serialize = function () {
  49022. return this._serialize({
  49023. name: "StateCondition",
  49024. properties: [
  49025. BABYLON.Action._GetTargetProperty(this._target),
  49026. { name: "value", value: this.value }
  49027. ]
  49028. });
  49029. };
  49030. return StateCondition;
  49031. }(Condition));
  49032. BABYLON.StateCondition = StateCondition;
  49033. })(BABYLON || (BABYLON = {}));
  49034. //# sourceMappingURL=babylon.condition.js.map
  49035. "use strict";
  49036. var BABYLON;
  49037. (function (BABYLON) {
  49038. /**
  49039. * The action to be carried out following a trigger
  49040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  49041. */
  49042. var Action = /** @class */ (function () {
  49043. /**
  49044. * Creates a new Action
  49045. * @param triggerOptions the trigger, with or without parameters, for the action
  49046. * @param condition an optional determinant of action
  49047. */
  49048. function Action(triggerOptions, condition) {
  49049. this.triggerOptions = triggerOptions;
  49050. /**
  49051. * An event triggered prior to action being executed.
  49052. * @type Observable
  49053. */
  49054. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49055. if (triggerOptions.parameter) {
  49056. this.trigger = triggerOptions.trigger;
  49057. this._triggerParameter = triggerOptions.parameter;
  49058. }
  49059. else {
  49060. this.trigger = triggerOptions;
  49061. }
  49062. this._nextActiveAction = this;
  49063. this._condition = condition;
  49064. }
  49065. /**
  49066. * Internal only
  49067. * @ignore
  49068. */
  49069. Action.prototype._prepare = function () {
  49070. };
  49071. /**
  49072. * Gets the trigger parameters
  49073. * @returns the trigger parameters
  49074. */
  49075. Action.prototype.getTriggerParameter = function () {
  49076. return this._triggerParameter;
  49077. };
  49078. /**
  49079. * Internal only - executes current action event
  49080. * @ignore
  49081. */
  49082. Action.prototype._executeCurrent = function (evt) {
  49083. if (this._nextActiveAction._condition) {
  49084. var condition = this._nextActiveAction._condition;
  49085. var currentRenderId = this._actionManager.getScene().getRenderId();
  49086. // We cache the current evaluation for the current frame
  49087. if (condition._evaluationId === currentRenderId) {
  49088. if (!condition._currentResult) {
  49089. return;
  49090. }
  49091. }
  49092. else {
  49093. condition._evaluationId = currentRenderId;
  49094. if (!condition.isValid()) {
  49095. condition._currentResult = false;
  49096. return;
  49097. }
  49098. condition._currentResult = true;
  49099. }
  49100. }
  49101. this.onBeforeExecuteObservable.notifyObservers(this);
  49102. this._nextActiveAction.execute(evt);
  49103. this.skipToNextActiveAction();
  49104. };
  49105. /**
  49106. * Execute placeholder for child classes
  49107. * @param evt optional action event
  49108. */
  49109. Action.prototype.execute = function (evt) {
  49110. };
  49111. /**
  49112. * Skips to next active action
  49113. */
  49114. Action.prototype.skipToNextActiveAction = function () {
  49115. if (this._nextActiveAction._child) {
  49116. if (!this._nextActiveAction._child._actionManager) {
  49117. this._nextActiveAction._child._actionManager = this._actionManager;
  49118. }
  49119. this._nextActiveAction = this._nextActiveAction._child;
  49120. }
  49121. else {
  49122. this._nextActiveAction = this;
  49123. }
  49124. };
  49125. /**
  49126. * Adds action to chain of actions, may be a DoNothingAction
  49127. * @param index The index of the attribute.
  49128. * @returns The action passed in
  49129. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49130. */
  49131. Action.prototype.then = function (action) {
  49132. this._child = action;
  49133. action._actionManager = this._actionManager;
  49134. action._prepare();
  49135. return action;
  49136. };
  49137. /**
  49138. * Internal only
  49139. * @ignore
  49140. */
  49141. Action.prototype._getProperty = function (propertyPath) {
  49142. return this._actionManager._getProperty(propertyPath);
  49143. };
  49144. /**
  49145. * Internal only
  49146. * @ignore
  49147. */
  49148. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49149. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49150. };
  49151. /**
  49152. * Serialize placeholder for child classes
  49153. * @param parent of child
  49154. * @returns the serialized object
  49155. */
  49156. Action.prototype.serialize = function (parent) {
  49157. };
  49158. /**
  49159. * Internal only called by serialize
  49160. * @ignore
  49161. */
  49162. Action.prototype._serialize = function (serializedAction, parent) {
  49163. var serializationObject = {
  49164. type: 1,
  49165. children: [],
  49166. name: serializedAction.name,
  49167. properties: serializedAction.properties || []
  49168. };
  49169. // Serialize child
  49170. if (this._child) {
  49171. this._child.serialize(serializationObject);
  49172. }
  49173. // Check if "this" has a condition
  49174. if (this._condition) {
  49175. var serializedCondition = this._condition.serialize();
  49176. serializedCondition.children.push(serializationObject);
  49177. if (parent) {
  49178. parent.children.push(serializedCondition);
  49179. }
  49180. return serializedCondition;
  49181. }
  49182. if (parent) {
  49183. parent.children.push(serializationObject);
  49184. }
  49185. return serializationObject;
  49186. };
  49187. /**
  49188. * Internal only
  49189. * @ignore
  49190. */
  49191. Action._SerializeValueAsString = function (value) {
  49192. if (typeof value === "number") {
  49193. return value.toString();
  49194. }
  49195. if (typeof value === "boolean") {
  49196. return value ? "true" : "false";
  49197. }
  49198. if (value instanceof BABYLON.Vector2) {
  49199. return value.x + ", " + value.y;
  49200. }
  49201. if (value instanceof BABYLON.Vector3) {
  49202. return value.x + ", " + value.y + ", " + value.z;
  49203. }
  49204. if (value instanceof BABYLON.Color3) {
  49205. return value.r + ", " + value.g + ", " + value.b;
  49206. }
  49207. if (value instanceof BABYLON.Color4) {
  49208. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49209. }
  49210. return value; // string
  49211. };
  49212. /**
  49213. * Internal only
  49214. * @ignore
  49215. */
  49216. Action._GetTargetProperty = function (target) {
  49217. return {
  49218. name: "target",
  49219. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49220. : target instanceof BABYLON.Light ? "LightProperties"
  49221. : target instanceof BABYLON.Camera ? "CameraProperties"
  49222. : "SceneProperties",
  49223. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49224. };
  49225. };
  49226. return Action;
  49227. }());
  49228. BABYLON.Action = Action;
  49229. })(BABYLON || (BABYLON = {}));
  49230. //# sourceMappingURL=babylon.action.js.map
  49231. "use strict";
  49232. var BABYLON;
  49233. (function (BABYLON) {
  49234. /**
  49235. * ActionEvent is the event being sent when an action is triggered.
  49236. */
  49237. var ActionEvent = /** @class */ (function () {
  49238. /**
  49239. * @param source The mesh or sprite that triggered the action.
  49240. * @param pointerX The X mouse cursor position at the time of the event
  49241. * @param pointerY The Y mouse cursor position at the time of the event
  49242. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49243. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49244. */
  49245. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49246. this.source = source;
  49247. this.pointerX = pointerX;
  49248. this.pointerY = pointerY;
  49249. this.meshUnderPointer = meshUnderPointer;
  49250. this.sourceEvent = sourceEvent;
  49251. this.additionalData = additionalData;
  49252. }
  49253. /**
  49254. * Helper function to auto-create an ActionEvent from a source mesh.
  49255. * @param source The source mesh that triggered the event
  49256. * @param evt {Event} The original (browser) event
  49257. */
  49258. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49259. var scene = source.getScene();
  49260. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49261. };
  49262. /**
  49263. * Helper function to auto-create an ActionEvent from a source mesh.
  49264. * @param source The source sprite that triggered the event
  49265. * @param scene Scene associated with the sprite
  49266. * @param evt {Event} The original (browser) event
  49267. */
  49268. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49269. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49270. };
  49271. /**
  49272. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49273. * @param scene the scene where the event occurred
  49274. * @param evt {Event} The original (browser) event
  49275. */
  49276. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49277. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49278. };
  49279. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49280. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49281. };
  49282. return ActionEvent;
  49283. }());
  49284. BABYLON.ActionEvent = ActionEvent;
  49285. /**
  49286. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49287. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49288. */
  49289. var ActionManager = /** @class */ (function () {
  49290. function ActionManager(scene) {
  49291. // Members
  49292. this.actions = new Array();
  49293. this.hoverCursor = '';
  49294. this._scene = scene;
  49295. scene._actionManagers.push(this);
  49296. }
  49297. Object.defineProperty(ActionManager, "NothingTrigger", {
  49298. get: function () {
  49299. return ActionManager._NothingTrigger;
  49300. },
  49301. enumerable: true,
  49302. configurable: true
  49303. });
  49304. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49305. get: function () {
  49306. return ActionManager._OnPickTrigger;
  49307. },
  49308. enumerable: true,
  49309. configurable: true
  49310. });
  49311. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49312. get: function () {
  49313. return ActionManager._OnLeftPickTrigger;
  49314. },
  49315. enumerable: true,
  49316. configurable: true
  49317. });
  49318. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49319. get: function () {
  49320. return ActionManager._OnRightPickTrigger;
  49321. },
  49322. enumerable: true,
  49323. configurable: true
  49324. });
  49325. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49326. get: function () {
  49327. return ActionManager._OnCenterPickTrigger;
  49328. },
  49329. enumerable: true,
  49330. configurable: true
  49331. });
  49332. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49333. get: function () {
  49334. return ActionManager._OnPickDownTrigger;
  49335. },
  49336. enumerable: true,
  49337. configurable: true
  49338. });
  49339. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49340. get: function () {
  49341. return ActionManager._OnDoublePickTrigger;
  49342. },
  49343. enumerable: true,
  49344. configurable: true
  49345. });
  49346. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49347. get: function () {
  49348. return ActionManager._OnPickUpTrigger;
  49349. },
  49350. enumerable: true,
  49351. configurable: true
  49352. });
  49353. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49354. /// This trigger will only be raised if you also declared a OnPickDown
  49355. get: function () {
  49356. return ActionManager._OnPickOutTrigger;
  49357. },
  49358. enumerable: true,
  49359. configurable: true
  49360. });
  49361. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49362. get: function () {
  49363. return ActionManager._OnLongPressTrigger;
  49364. },
  49365. enumerable: true,
  49366. configurable: true
  49367. });
  49368. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49369. get: function () {
  49370. return ActionManager._OnPointerOverTrigger;
  49371. },
  49372. enumerable: true,
  49373. configurable: true
  49374. });
  49375. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49376. get: function () {
  49377. return ActionManager._OnPointerOutTrigger;
  49378. },
  49379. enumerable: true,
  49380. configurable: true
  49381. });
  49382. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49383. get: function () {
  49384. return ActionManager._OnEveryFrameTrigger;
  49385. },
  49386. enumerable: true,
  49387. configurable: true
  49388. });
  49389. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49390. get: function () {
  49391. return ActionManager._OnIntersectionEnterTrigger;
  49392. },
  49393. enumerable: true,
  49394. configurable: true
  49395. });
  49396. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49397. get: function () {
  49398. return ActionManager._OnIntersectionExitTrigger;
  49399. },
  49400. enumerable: true,
  49401. configurable: true
  49402. });
  49403. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49404. get: function () {
  49405. return ActionManager._OnKeyDownTrigger;
  49406. },
  49407. enumerable: true,
  49408. configurable: true
  49409. });
  49410. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49411. get: function () {
  49412. return ActionManager._OnKeyUpTrigger;
  49413. },
  49414. enumerable: true,
  49415. configurable: true
  49416. });
  49417. // Methods
  49418. ActionManager.prototype.dispose = function () {
  49419. var index = this._scene._actionManagers.indexOf(this);
  49420. for (var i = 0; i < this.actions.length; i++) {
  49421. var action = this.actions[i];
  49422. ActionManager.Triggers[action.trigger]--;
  49423. if (ActionManager.Triggers[action.trigger] === 0) {
  49424. delete ActionManager.Triggers[action.trigger];
  49425. }
  49426. }
  49427. if (index > -1) {
  49428. this._scene._actionManagers.splice(index, 1);
  49429. }
  49430. };
  49431. ActionManager.prototype.getScene = function () {
  49432. return this._scene;
  49433. };
  49434. /**
  49435. * Does this action manager handles actions of any of the given triggers
  49436. * @param {number[]} triggers - the triggers to be tested
  49437. * @return {boolean} whether one (or more) of the triggers is handeled
  49438. */
  49439. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49440. for (var index = 0; index < this.actions.length; index++) {
  49441. var action = this.actions[index];
  49442. if (triggers.indexOf(action.trigger) > -1) {
  49443. return true;
  49444. }
  49445. }
  49446. return false;
  49447. };
  49448. /**
  49449. * Does this action manager handles actions of a given trigger
  49450. * @param {number} trigger - the trigger to be tested
  49451. * @return {boolean} whether the trigger is handeled
  49452. */
  49453. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49454. for (var index = 0; index < this.actions.length; index++) {
  49455. var action = this.actions[index];
  49456. if (action.trigger === trigger) {
  49457. return true;
  49458. }
  49459. }
  49460. return false;
  49461. };
  49462. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49463. /**
  49464. * Does this action manager has pointer triggers
  49465. * @return {boolean} whether or not it has pointer triggers
  49466. */
  49467. get: function () {
  49468. for (var index = 0; index < this.actions.length; index++) {
  49469. var action = this.actions[index];
  49470. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49471. return true;
  49472. }
  49473. }
  49474. return false;
  49475. },
  49476. enumerable: true,
  49477. configurable: true
  49478. });
  49479. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49480. /**
  49481. * Does this action manager has pick triggers
  49482. * @return {boolean} whether or not it has pick triggers
  49483. */
  49484. get: function () {
  49485. for (var index = 0; index < this.actions.length; index++) {
  49486. var action = this.actions[index];
  49487. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49488. return true;
  49489. }
  49490. }
  49491. return false;
  49492. },
  49493. enumerable: true,
  49494. configurable: true
  49495. });
  49496. Object.defineProperty(ActionManager, "HasTriggers", {
  49497. /**
  49498. * Does exist one action manager with at least one trigger
  49499. * @return {boolean} whether or not it exists one action manager with one trigger
  49500. **/
  49501. get: function () {
  49502. for (var t in ActionManager.Triggers) {
  49503. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49504. return true;
  49505. }
  49506. }
  49507. return false;
  49508. },
  49509. enumerable: true,
  49510. configurable: true
  49511. });
  49512. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49513. /**
  49514. * Does exist one action manager with at least one pick trigger
  49515. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49516. **/
  49517. get: function () {
  49518. for (var t in ActionManager.Triggers) {
  49519. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49520. var t_int = parseInt(t);
  49521. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49522. return true;
  49523. }
  49524. }
  49525. }
  49526. return false;
  49527. },
  49528. enumerable: true,
  49529. configurable: true
  49530. });
  49531. /**
  49532. * Does exist one action manager that handles actions of a given trigger
  49533. * @param {number} trigger - the trigger to be tested
  49534. * @return {boolean} whether the trigger is handeled by at least one action manager
  49535. **/
  49536. ActionManager.HasSpecificTrigger = function (trigger) {
  49537. for (var t in ActionManager.Triggers) {
  49538. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49539. var t_int = parseInt(t);
  49540. if (t_int === trigger) {
  49541. return true;
  49542. }
  49543. }
  49544. }
  49545. return false;
  49546. };
  49547. /**
  49548. * Registers an action to this action manager
  49549. * @param {BABYLON.Action} action - the action to be registered
  49550. * @return {BABYLON.Action} the action amended (prepared) after registration
  49551. */
  49552. ActionManager.prototype.registerAction = function (action) {
  49553. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49554. if (this.getScene().actionManager !== this) {
  49555. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49556. return null;
  49557. }
  49558. }
  49559. this.actions.push(action);
  49560. if (ActionManager.Triggers[action.trigger]) {
  49561. ActionManager.Triggers[action.trigger]++;
  49562. }
  49563. else {
  49564. ActionManager.Triggers[action.trigger] = 1;
  49565. }
  49566. action._actionManager = this;
  49567. action._prepare();
  49568. return action;
  49569. };
  49570. /**
  49571. * Unregisters an action to this action manager
  49572. * @param action The action to be unregistered
  49573. * @return whether the action has been unregistered
  49574. */
  49575. ActionManager.prototype.unregisterAction = function (action) {
  49576. var index = this.actions.indexOf(action);
  49577. if (index !== -1) {
  49578. this.actions.splice(index, 1);
  49579. ActionManager.Triggers[action.trigger] -= 1;
  49580. if (ActionManager.Triggers[action.trigger] === 0) {
  49581. delete ActionManager.Triggers[action.trigger];
  49582. }
  49583. delete action._actionManager;
  49584. return true;
  49585. }
  49586. return false;
  49587. };
  49588. /**
  49589. * Process a specific trigger
  49590. * @param {number} trigger - the trigger to process
  49591. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49592. */
  49593. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49594. for (var index = 0; index < this.actions.length; index++) {
  49595. var action = this.actions[index];
  49596. if (action.trigger === trigger) {
  49597. if (evt) {
  49598. if (trigger === ActionManager.OnKeyUpTrigger
  49599. || trigger === ActionManager.OnKeyDownTrigger) {
  49600. var parameter = action.getTriggerParameter();
  49601. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49602. if (!parameter.toLowerCase) {
  49603. continue;
  49604. }
  49605. var lowerCase = parameter.toLowerCase();
  49606. if (lowerCase !== evt.sourceEvent.key) {
  49607. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49608. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49609. if (actualkey !== lowerCase) {
  49610. continue;
  49611. }
  49612. }
  49613. }
  49614. }
  49615. }
  49616. action._executeCurrent(evt);
  49617. }
  49618. }
  49619. };
  49620. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49621. var properties = propertyPath.split(".");
  49622. for (var index = 0; index < properties.length - 1; index++) {
  49623. target = target[properties[index]];
  49624. }
  49625. return target;
  49626. };
  49627. ActionManager.prototype._getProperty = function (propertyPath) {
  49628. var properties = propertyPath.split(".");
  49629. return properties[properties.length - 1];
  49630. };
  49631. ActionManager.prototype.serialize = function (name) {
  49632. var root = {
  49633. children: new Array(),
  49634. name: name,
  49635. type: 3,
  49636. properties: new Array() // Empty for root but required
  49637. };
  49638. for (var i = 0; i < this.actions.length; i++) {
  49639. var triggerObject = {
  49640. type: 0,
  49641. children: new Array(),
  49642. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49643. properties: new Array()
  49644. };
  49645. var triggerOptions = this.actions[i].triggerOptions;
  49646. if (triggerOptions && typeof triggerOptions !== "number") {
  49647. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49648. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49649. }
  49650. else {
  49651. var parameter = {};
  49652. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49653. if (triggerOptions.parameter.mesh) {
  49654. parameter._meshId = triggerOptions.parameter.mesh.id;
  49655. }
  49656. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49657. }
  49658. }
  49659. // Serialize child action, recursively
  49660. this.actions[i].serialize(triggerObject);
  49661. // Add serialized trigger
  49662. root.children.push(triggerObject);
  49663. }
  49664. return root;
  49665. };
  49666. ActionManager.Parse = function (parsedActions, object, scene) {
  49667. var actionManager = new ActionManager(scene);
  49668. if (object === null)
  49669. scene.actionManager = actionManager;
  49670. else
  49671. object.actionManager = actionManager;
  49672. // instanciate a new object
  49673. var instanciate = function (name, params) {
  49674. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49675. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49676. newInstance.constructor.apply(newInstance, params);
  49677. return newInstance;
  49678. };
  49679. var parseParameter = function (name, value, target, propertyPath) {
  49680. if (propertyPath === null) {
  49681. // String, boolean or float
  49682. var floatValue = parseFloat(value);
  49683. if (value === "true" || value === "false")
  49684. return value === "true";
  49685. else
  49686. return isNaN(floatValue) ? value : floatValue;
  49687. }
  49688. var effectiveTarget = propertyPath.split(".");
  49689. var values = value.split(",");
  49690. // Get effective Target
  49691. for (var i = 0; i < effectiveTarget.length; i++) {
  49692. target = target[effectiveTarget[i]];
  49693. }
  49694. // Return appropriate value with its type
  49695. if (typeof (target) === "boolean")
  49696. return values[0] === "true";
  49697. if (typeof (target) === "string")
  49698. return values[0];
  49699. // Parameters with multiple values such as Vector3 etc.
  49700. var split = new Array();
  49701. for (var i = 0; i < values.length; i++)
  49702. split.push(parseFloat(values[i]));
  49703. if (target instanceof BABYLON.Vector3)
  49704. return BABYLON.Vector3.FromArray(split);
  49705. if (target instanceof BABYLON.Vector4)
  49706. return BABYLON.Vector4.FromArray(split);
  49707. if (target instanceof BABYLON.Color3)
  49708. return BABYLON.Color3.FromArray(split);
  49709. if (target instanceof BABYLON.Color4)
  49710. return BABYLON.Color4.FromArray(split);
  49711. return parseFloat(values[0]);
  49712. };
  49713. // traverse graph per trigger
  49714. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49715. if (combineArray === void 0) { combineArray = null; }
  49716. if (parsedAction.detached)
  49717. return;
  49718. var parameters = new Array();
  49719. var target = null;
  49720. var propertyPath = null;
  49721. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49722. // Parameters
  49723. if (parsedAction.type === 2)
  49724. parameters.push(actionManager);
  49725. else
  49726. parameters.push(trigger);
  49727. if (combine) {
  49728. var actions = new Array();
  49729. for (var j = 0; j < parsedAction.combine.length; j++) {
  49730. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49731. }
  49732. parameters.push(actions);
  49733. }
  49734. else {
  49735. for (var i = 0; i < parsedAction.properties.length; i++) {
  49736. var value = parsedAction.properties[i].value;
  49737. var name = parsedAction.properties[i].name;
  49738. var targetType = parsedAction.properties[i].targetType;
  49739. if (name === "target")
  49740. if (targetType !== null && targetType === "SceneProperties")
  49741. value = target = scene;
  49742. else
  49743. value = target = scene.getNodeByName(value);
  49744. else if (name === "parent")
  49745. value = scene.getNodeByName(value);
  49746. else if (name === "sound")
  49747. value = scene.getSoundByName(value);
  49748. else if (name !== "propertyPath") {
  49749. if (parsedAction.type === 2 && name === "operator")
  49750. value = BABYLON.ValueCondition[value];
  49751. else
  49752. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49753. }
  49754. else {
  49755. propertyPath = value;
  49756. }
  49757. parameters.push(value);
  49758. }
  49759. }
  49760. if (combineArray === null) {
  49761. parameters.push(condition);
  49762. }
  49763. else {
  49764. parameters.push(null);
  49765. }
  49766. // If interpolate value action
  49767. if (parsedAction.name === "InterpolateValueAction") {
  49768. var param = parameters[parameters.length - 2];
  49769. parameters[parameters.length - 1] = param;
  49770. parameters[parameters.length - 2] = condition;
  49771. }
  49772. // Action or condition(s) and not CombineAction
  49773. var newAction = instanciate(parsedAction.name, parameters);
  49774. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49775. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49776. if (action)
  49777. action.then(nothing);
  49778. else
  49779. actionManager.registerAction(nothing);
  49780. action = nothing;
  49781. }
  49782. if (combineArray === null) {
  49783. if (newAction instanceof BABYLON.Condition) {
  49784. condition = newAction;
  49785. newAction = action;
  49786. }
  49787. else {
  49788. condition = null;
  49789. if (action)
  49790. action.then(newAction);
  49791. else
  49792. actionManager.registerAction(newAction);
  49793. }
  49794. }
  49795. else {
  49796. combineArray.push(newAction);
  49797. }
  49798. for (var i = 0; i < parsedAction.children.length; i++)
  49799. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49800. };
  49801. // triggers
  49802. for (var i = 0; i < parsedActions.children.length; i++) {
  49803. var triggerParams;
  49804. var trigger = parsedActions.children[i];
  49805. if (trigger.properties.length > 0) {
  49806. var param = trigger.properties[0].value;
  49807. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49808. if (value._meshId) {
  49809. value.mesh = scene.getMeshByID(value._meshId);
  49810. }
  49811. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49812. }
  49813. else
  49814. triggerParams = ActionManager[trigger.name];
  49815. for (var j = 0; j < trigger.children.length; j++) {
  49816. if (!trigger.detached)
  49817. traverse(trigger.children[j], triggerParams, null, null);
  49818. }
  49819. }
  49820. };
  49821. ActionManager.GetTriggerName = function (trigger) {
  49822. switch (trigger) {
  49823. case 0: return "NothingTrigger";
  49824. case 1: return "OnPickTrigger";
  49825. case 2: return "OnLeftPickTrigger";
  49826. case 3: return "OnRightPickTrigger";
  49827. case 4: return "OnCenterPickTrigger";
  49828. case 5: return "OnPickDownTrigger";
  49829. case 6: return "OnPickUpTrigger";
  49830. case 7: return "OnLongPressTrigger";
  49831. case 8: return "OnPointerOverTrigger";
  49832. case 9: return "OnPointerOutTrigger";
  49833. case 10: return "OnEveryFrameTrigger";
  49834. case 11: return "OnIntersectionEnterTrigger";
  49835. case 12: return "OnIntersectionExitTrigger";
  49836. case 13: return "OnKeyDownTrigger";
  49837. case 14: return "OnKeyUpTrigger";
  49838. case 15: return "OnPickOutTrigger";
  49839. default: return "";
  49840. }
  49841. };
  49842. // Statics
  49843. ActionManager._NothingTrigger = 0;
  49844. ActionManager._OnPickTrigger = 1;
  49845. ActionManager._OnLeftPickTrigger = 2;
  49846. ActionManager._OnRightPickTrigger = 3;
  49847. ActionManager._OnCenterPickTrigger = 4;
  49848. ActionManager._OnPickDownTrigger = 5;
  49849. ActionManager._OnDoublePickTrigger = 6;
  49850. ActionManager._OnPickUpTrigger = 7;
  49851. ActionManager._OnLongPressTrigger = 8;
  49852. ActionManager._OnPointerOverTrigger = 9;
  49853. ActionManager._OnPointerOutTrigger = 10;
  49854. ActionManager._OnEveryFrameTrigger = 11;
  49855. ActionManager._OnIntersectionEnterTrigger = 12;
  49856. ActionManager._OnIntersectionExitTrigger = 13;
  49857. ActionManager._OnKeyDownTrigger = 14;
  49858. ActionManager._OnKeyUpTrigger = 15;
  49859. ActionManager._OnPickOutTrigger = 16;
  49860. ActionManager.Triggers = {};
  49861. return ActionManager;
  49862. }());
  49863. BABYLON.ActionManager = ActionManager;
  49864. })(BABYLON || (BABYLON = {}));
  49865. //# sourceMappingURL=babylon.actionManager.js.map
  49866. "use strict";
  49867. var BABYLON;
  49868. (function (BABYLON) {
  49869. var InterpolateValueAction = /** @class */ (function (_super) {
  49870. __extends(InterpolateValueAction, _super);
  49871. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49872. if (duration === void 0) { duration = 1000; }
  49873. var _this = _super.call(this, triggerOptions, condition) || this;
  49874. _this.propertyPath = propertyPath;
  49875. _this.value = value;
  49876. _this.duration = duration;
  49877. _this.stopOtherAnimations = stopOtherAnimations;
  49878. _this.onInterpolationDone = onInterpolationDone;
  49879. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49880. _this._target = _this._effectiveTarget = target;
  49881. return _this;
  49882. }
  49883. InterpolateValueAction.prototype._prepare = function () {
  49884. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49885. this._property = this._getProperty(this.propertyPath);
  49886. };
  49887. InterpolateValueAction.prototype.execute = function () {
  49888. var _this = this;
  49889. var scene = this._actionManager.getScene();
  49890. var keys = [
  49891. {
  49892. frame: 0,
  49893. value: this._effectiveTarget[this._property]
  49894. }, {
  49895. frame: 100,
  49896. value: this.value
  49897. }
  49898. ];
  49899. var dataType;
  49900. if (typeof this.value === "number") {
  49901. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49902. }
  49903. else if (this.value instanceof BABYLON.Color3) {
  49904. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49905. }
  49906. else if (this.value instanceof BABYLON.Vector3) {
  49907. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49908. }
  49909. else if (this.value instanceof BABYLON.Matrix) {
  49910. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49911. }
  49912. else if (this.value instanceof BABYLON.Quaternion) {
  49913. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49914. }
  49915. else {
  49916. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49917. return;
  49918. }
  49919. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49920. animation.setKeys(keys);
  49921. if (this.stopOtherAnimations) {
  49922. scene.stopAnimation(this._effectiveTarget);
  49923. }
  49924. var wrapper = function () {
  49925. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49926. if (_this.onInterpolationDone) {
  49927. _this.onInterpolationDone();
  49928. }
  49929. };
  49930. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49931. };
  49932. InterpolateValueAction.prototype.serialize = function (parent) {
  49933. return _super.prototype._serialize.call(this, {
  49934. name: "InterpolateValueAction",
  49935. properties: [
  49936. BABYLON.Action._GetTargetProperty(this._target),
  49937. { name: "propertyPath", value: this.propertyPath },
  49938. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49939. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49940. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49941. ]
  49942. }, parent);
  49943. };
  49944. return InterpolateValueAction;
  49945. }(BABYLON.Action));
  49946. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49947. })(BABYLON || (BABYLON = {}));
  49948. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49949. "use strict";
  49950. var BABYLON;
  49951. (function (BABYLON) {
  49952. var SwitchBooleanAction = /** @class */ (function (_super) {
  49953. __extends(SwitchBooleanAction, _super);
  49954. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49955. var _this = _super.call(this, triggerOptions, condition) || this;
  49956. _this.propertyPath = propertyPath;
  49957. _this._target = _this._effectiveTarget = target;
  49958. return _this;
  49959. }
  49960. SwitchBooleanAction.prototype._prepare = function () {
  49961. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49962. this._property = this._getProperty(this.propertyPath);
  49963. };
  49964. SwitchBooleanAction.prototype.execute = function () {
  49965. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49966. };
  49967. SwitchBooleanAction.prototype.serialize = function (parent) {
  49968. return _super.prototype._serialize.call(this, {
  49969. name: "SwitchBooleanAction",
  49970. properties: [
  49971. BABYLON.Action._GetTargetProperty(this._target),
  49972. { name: "propertyPath", value: this.propertyPath }
  49973. ]
  49974. }, parent);
  49975. };
  49976. return SwitchBooleanAction;
  49977. }(BABYLON.Action));
  49978. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49979. var SetStateAction = /** @class */ (function (_super) {
  49980. __extends(SetStateAction, _super);
  49981. function SetStateAction(triggerOptions, target, value, condition) {
  49982. var _this = _super.call(this, triggerOptions, condition) || this;
  49983. _this.value = value;
  49984. _this._target = target;
  49985. return _this;
  49986. }
  49987. SetStateAction.prototype.execute = function () {
  49988. this._target.state = this.value;
  49989. };
  49990. SetStateAction.prototype.serialize = function (parent) {
  49991. return _super.prototype._serialize.call(this, {
  49992. name: "SetStateAction",
  49993. properties: [
  49994. BABYLON.Action._GetTargetProperty(this._target),
  49995. { name: "value", value: this.value }
  49996. ]
  49997. }, parent);
  49998. };
  49999. return SetStateAction;
  50000. }(BABYLON.Action));
  50001. BABYLON.SetStateAction = SetStateAction;
  50002. var SetValueAction = /** @class */ (function (_super) {
  50003. __extends(SetValueAction, _super);
  50004. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  50005. var _this = _super.call(this, triggerOptions, condition) || this;
  50006. _this.propertyPath = propertyPath;
  50007. _this.value = value;
  50008. _this._target = _this._effectiveTarget = target;
  50009. return _this;
  50010. }
  50011. SetValueAction.prototype._prepare = function () {
  50012. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50013. this._property = this._getProperty(this.propertyPath);
  50014. };
  50015. SetValueAction.prototype.execute = function () {
  50016. this._effectiveTarget[this._property] = this.value;
  50017. if (this._target.markAsDirty) {
  50018. this._target.markAsDirty(this._property);
  50019. }
  50020. };
  50021. SetValueAction.prototype.serialize = function (parent) {
  50022. return _super.prototype._serialize.call(this, {
  50023. name: "SetValueAction",
  50024. properties: [
  50025. BABYLON.Action._GetTargetProperty(this._target),
  50026. { name: "propertyPath", value: this.propertyPath },
  50027. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50028. ]
  50029. }, parent);
  50030. };
  50031. return SetValueAction;
  50032. }(BABYLON.Action));
  50033. BABYLON.SetValueAction = SetValueAction;
  50034. var IncrementValueAction = /** @class */ (function (_super) {
  50035. __extends(IncrementValueAction, _super);
  50036. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  50037. var _this = _super.call(this, triggerOptions, condition) || this;
  50038. _this.propertyPath = propertyPath;
  50039. _this.value = value;
  50040. _this._target = _this._effectiveTarget = target;
  50041. return _this;
  50042. }
  50043. IncrementValueAction.prototype._prepare = function () {
  50044. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50045. this._property = this._getProperty(this.propertyPath);
  50046. if (typeof this._effectiveTarget[this._property] !== "number") {
  50047. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  50048. }
  50049. };
  50050. IncrementValueAction.prototype.execute = function () {
  50051. this._effectiveTarget[this._property] += this.value;
  50052. if (this._target.markAsDirty) {
  50053. this._target.markAsDirty(this._property);
  50054. }
  50055. };
  50056. IncrementValueAction.prototype.serialize = function (parent) {
  50057. return _super.prototype._serialize.call(this, {
  50058. name: "IncrementValueAction",
  50059. properties: [
  50060. BABYLON.Action._GetTargetProperty(this._target),
  50061. { name: "propertyPath", value: this.propertyPath },
  50062. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50063. ]
  50064. }, parent);
  50065. };
  50066. return IncrementValueAction;
  50067. }(BABYLON.Action));
  50068. BABYLON.IncrementValueAction = IncrementValueAction;
  50069. var PlayAnimationAction = /** @class */ (function (_super) {
  50070. __extends(PlayAnimationAction, _super);
  50071. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50072. var _this = _super.call(this, triggerOptions, condition) || this;
  50073. _this.from = from;
  50074. _this.to = to;
  50075. _this.loop = loop;
  50076. _this._target = target;
  50077. return _this;
  50078. }
  50079. PlayAnimationAction.prototype._prepare = function () {
  50080. };
  50081. PlayAnimationAction.prototype.execute = function () {
  50082. var scene = this._actionManager.getScene();
  50083. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50084. };
  50085. PlayAnimationAction.prototype.serialize = function (parent) {
  50086. return _super.prototype._serialize.call(this, {
  50087. name: "PlayAnimationAction",
  50088. properties: [
  50089. BABYLON.Action._GetTargetProperty(this._target),
  50090. { name: "from", value: String(this.from) },
  50091. { name: "to", value: String(this.to) },
  50092. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50093. ]
  50094. }, parent);
  50095. };
  50096. return PlayAnimationAction;
  50097. }(BABYLON.Action));
  50098. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50099. var StopAnimationAction = /** @class */ (function (_super) {
  50100. __extends(StopAnimationAction, _super);
  50101. function StopAnimationAction(triggerOptions, target, condition) {
  50102. var _this = _super.call(this, triggerOptions, condition) || this;
  50103. _this._target = target;
  50104. return _this;
  50105. }
  50106. StopAnimationAction.prototype._prepare = function () {
  50107. };
  50108. StopAnimationAction.prototype.execute = function () {
  50109. var scene = this._actionManager.getScene();
  50110. scene.stopAnimation(this._target);
  50111. };
  50112. StopAnimationAction.prototype.serialize = function (parent) {
  50113. return _super.prototype._serialize.call(this, {
  50114. name: "StopAnimationAction",
  50115. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50116. }, parent);
  50117. };
  50118. return StopAnimationAction;
  50119. }(BABYLON.Action));
  50120. BABYLON.StopAnimationAction = StopAnimationAction;
  50121. var DoNothingAction = /** @class */ (function (_super) {
  50122. __extends(DoNothingAction, _super);
  50123. function DoNothingAction(triggerOptions, condition) {
  50124. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50125. return _super.call(this, triggerOptions, condition) || this;
  50126. }
  50127. DoNothingAction.prototype.execute = function () {
  50128. };
  50129. DoNothingAction.prototype.serialize = function (parent) {
  50130. return _super.prototype._serialize.call(this, {
  50131. name: "DoNothingAction",
  50132. properties: []
  50133. }, parent);
  50134. };
  50135. return DoNothingAction;
  50136. }(BABYLON.Action));
  50137. BABYLON.DoNothingAction = DoNothingAction;
  50138. var CombineAction = /** @class */ (function (_super) {
  50139. __extends(CombineAction, _super);
  50140. function CombineAction(triggerOptions, children, condition) {
  50141. var _this = _super.call(this, triggerOptions, condition) || this;
  50142. _this.children = children;
  50143. return _this;
  50144. }
  50145. CombineAction.prototype._prepare = function () {
  50146. for (var index = 0; index < this.children.length; index++) {
  50147. this.children[index]._actionManager = this._actionManager;
  50148. this.children[index]._prepare();
  50149. }
  50150. };
  50151. CombineAction.prototype.execute = function (evt) {
  50152. for (var index = 0; index < this.children.length; index++) {
  50153. this.children[index].execute(evt);
  50154. }
  50155. };
  50156. CombineAction.prototype.serialize = function (parent) {
  50157. var serializationObject = _super.prototype._serialize.call(this, {
  50158. name: "CombineAction",
  50159. properties: [],
  50160. combine: []
  50161. }, parent);
  50162. for (var i = 0; i < this.children.length; i++) {
  50163. serializationObject.combine.push(this.children[i].serialize(null));
  50164. }
  50165. return serializationObject;
  50166. };
  50167. return CombineAction;
  50168. }(BABYLON.Action));
  50169. BABYLON.CombineAction = CombineAction;
  50170. var ExecuteCodeAction = /** @class */ (function (_super) {
  50171. __extends(ExecuteCodeAction, _super);
  50172. function ExecuteCodeAction(triggerOptions, func, condition) {
  50173. var _this = _super.call(this, triggerOptions, condition) || this;
  50174. _this.func = func;
  50175. return _this;
  50176. }
  50177. ExecuteCodeAction.prototype.execute = function (evt) {
  50178. this.func(evt);
  50179. };
  50180. return ExecuteCodeAction;
  50181. }(BABYLON.Action));
  50182. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50183. var SetParentAction = /** @class */ (function (_super) {
  50184. __extends(SetParentAction, _super);
  50185. function SetParentAction(triggerOptions, target, parent, condition) {
  50186. var _this = _super.call(this, triggerOptions, condition) || this;
  50187. _this._target = target;
  50188. _this._parent = parent;
  50189. return _this;
  50190. }
  50191. SetParentAction.prototype._prepare = function () {
  50192. };
  50193. SetParentAction.prototype.execute = function () {
  50194. if (this._target.parent === this._parent) {
  50195. return;
  50196. }
  50197. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50198. invertParentWorldMatrix.invert();
  50199. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50200. this._target.parent = this._parent;
  50201. };
  50202. SetParentAction.prototype.serialize = function (parent) {
  50203. return _super.prototype._serialize.call(this, {
  50204. name: "SetParentAction",
  50205. properties: [
  50206. BABYLON.Action._GetTargetProperty(this._target),
  50207. BABYLON.Action._GetTargetProperty(this._parent),
  50208. ]
  50209. }, parent);
  50210. };
  50211. return SetParentAction;
  50212. }(BABYLON.Action));
  50213. BABYLON.SetParentAction = SetParentAction;
  50214. var PlaySoundAction = /** @class */ (function (_super) {
  50215. __extends(PlaySoundAction, _super);
  50216. function PlaySoundAction(triggerOptions, sound, condition) {
  50217. var _this = _super.call(this, triggerOptions, condition) || this;
  50218. _this._sound = sound;
  50219. return _this;
  50220. }
  50221. PlaySoundAction.prototype._prepare = function () {
  50222. };
  50223. PlaySoundAction.prototype.execute = function () {
  50224. if (this._sound !== undefined)
  50225. this._sound.play();
  50226. };
  50227. PlaySoundAction.prototype.serialize = function (parent) {
  50228. return _super.prototype._serialize.call(this, {
  50229. name: "PlaySoundAction",
  50230. properties: [{ name: "sound", value: this._sound.name }]
  50231. }, parent);
  50232. };
  50233. return PlaySoundAction;
  50234. }(BABYLON.Action));
  50235. BABYLON.PlaySoundAction = PlaySoundAction;
  50236. var StopSoundAction = /** @class */ (function (_super) {
  50237. __extends(StopSoundAction, _super);
  50238. function StopSoundAction(triggerOptions, sound, condition) {
  50239. var _this = _super.call(this, triggerOptions, condition) || this;
  50240. _this._sound = sound;
  50241. return _this;
  50242. }
  50243. StopSoundAction.prototype._prepare = function () {
  50244. };
  50245. StopSoundAction.prototype.execute = function () {
  50246. if (this._sound !== undefined)
  50247. this._sound.stop();
  50248. };
  50249. StopSoundAction.prototype.serialize = function (parent) {
  50250. return _super.prototype._serialize.call(this, {
  50251. name: "StopSoundAction",
  50252. properties: [{ name: "sound", value: this._sound.name }]
  50253. }, parent);
  50254. };
  50255. return StopSoundAction;
  50256. }(BABYLON.Action));
  50257. BABYLON.StopSoundAction = StopSoundAction;
  50258. })(BABYLON || (BABYLON = {}));
  50259. //# sourceMappingURL=babylon.directActions.js.map
  50260. "use strict";
  50261. var BABYLON;
  50262. (function (BABYLON) {
  50263. var SpriteManager = /** @class */ (function () {
  50264. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50265. if (epsilon === void 0) { epsilon = 0.01; }
  50266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50267. this.name = name;
  50268. this.sprites = new Array();
  50269. this.renderingGroupId = 0;
  50270. this.layerMask = 0x0FFFFFFF;
  50271. this.fogEnabled = true;
  50272. this.isPickable = false;
  50273. /**
  50274. * An event triggered when the manager is disposed.
  50275. * @type {BABYLON.Observable}
  50276. */
  50277. this.onDisposeObservable = new BABYLON.Observable();
  50278. this._vertexBuffers = {};
  50279. this._capacity = capacity;
  50280. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50281. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50282. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50283. if (cellSize.width && cellSize.height) {
  50284. this.cellWidth = cellSize.width;
  50285. this.cellHeight = cellSize.height;
  50286. }
  50287. else if (cellSize !== undefined) {
  50288. this.cellWidth = cellSize;
  50289. this.cellHeight = cellSize;
  50290. }
  50291. else {
  50292. return;
  50293. }
  50294. this._epsilon = epsilon;
  50295. this._scene = scene;
  50296. this._scene.spriteManagers.push(this);
  50297. var indices = [];
  50298. var index = 0;
  50299. for (var count = 0; count < capacity; count++) {
  50300. indices.push(index);
  50301. indices.push(index + 1);
  50302. indices.push(index + 2);
  50303. indices.push(index);
  50304. indices.push(index + 2);
  50305. indices.push(index + 3);
  50306. index += 4;
  50307. }
  50308. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50309. // VBO
  50310. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50311. this._vertexData = new Float32Array(capacity * 16 * 4);
  50312. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50313. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50314. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50315. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50316. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50317. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50318. this._vertexBuffers["options"] = options;
  50319. this._vertexBuffers["cellInfo"] = cellInfo;
  50320. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50321. // Effects
  50322. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50323. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50324. }
  50325. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50326. set: function (callback) {
  50327. if (this._onDisposeObserver) {
  50328. this.onDisposeObservable.remove(this._onDisposeObserver);
  50329. }
  50330. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. Object.defineProperty(SpriteManager.prototype, "texture", {
  50336. get: function () {
  50337. return this._spriteTexture;
  50338. },
  50339. set: function (value) {
  50340. this._spriteTexture = value;
  50341. },
  50342. enumerable: true,
  50343. configurable: true
  50344. });
  50345. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50346. var arrayOffset = index * 16;
  50347. if (offsetX === 0)
  50348. offsetX = this._epsilon;
  50349. else if (offsetX === 1)
  50350. offsetX = 1 - this._epsilon;
  50351. if (offsetY === 0)
  50352. offsetY = this._epsilon;
  50353. else if (offsetY === 1)
  50354. offsetY = 1 - this._epsilon;
  50355. this._vertexData[arrayOffset] = sprite.position.x;
  50356. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50357. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50358. this._vertexData[arrayOffset + 3] = sprite.angle;
  50359. this._vertexData[arrayOffset + 4] = sprite.width;
  50360. this._vertexData[arrayOffset + 5] = sprite.height;
  50361. this._vertexData[arrayOffset + 6] = offsetX;
  50362. this._vertexData[arrayOffset + 7] = offsetY;
  50363. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50364. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50365. var offset = (sprite.cellIndex / rowSize) >> 0;
  50366. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50367. this._vertexData[arrayOffset + 11] = offset;
  50368. // Color
  50369. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50370. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50371. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50372. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50373. };
  50374. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50375. var count = Math.min(this._capacity, this.sprites.length);
  50376. var min = BABYLON.Vector3.Zero();
  50377. var max = BABYLON.Vector3.Zero();
  50378. var distance = Number.MAX_VALUE;
  50379. var currentSprite = null;
  50380. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50381. var cameraView = camera.getViewMatrix();
  50382. for (var index = 0; index < count; index++) {
  50383. var sprite = this.sprites[index];
  50384. if (!sprite) {
  50385. continue;
  50386. }
  50387. if (predicate) {
  50388. if (!predicate(sprite)) {
  50389. continue;
  50390. }
  50391. }
  50392. else if (!sprite.isPickable) {
  50393. continue;
  50394. }
  50395. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50396. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50397. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50398. if (ray.intersectsBoxMinMax(min, max)) {
  50399. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50400. if (distance > currentDistance) {
  50401. distance = currentDistance;
  50402. currentSprite = sprite;
  50403. if (fastCheck) {
  50404. break;
  50405. }
  50406. }
  50407. }
  50408. }
  50409. if (currentSprite) {
  50410. var result = new BABYLON.PickingInfo();
  50411. result.hit = true;
  50412. result.pickedSprite = currentSprite;
  50413. result.distance = distance;
  50414. return result;
  50415. }
  50416. return null;
  50417. };
  50418. SpriteManager.prototype.render = function () {
  50419. // Check
  50420. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50421. return;
  50422. var engine = this._scene.getEngine();
  50423. var baseSize = this._spriteTexture.getBaseSize();
  50424. // Sprites
  50425. var deltaTime = engine.getDeltaTime();
  50426. var max = Math.min(this._capacity, this.sprites.length);
  50427. var rowSize = baseSize.width / this.cellWidth;
  50428. var offset = 0;
  50429. for (var index = 0; index < max; index++) {
  50430. var sprite = this.sprites[index];
  50431. if (!sprite) {
  50432. continue;
  50433. }
  50434. sprite._animate(deltaTime);
  50435. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50436. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50437. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50438. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50439. }
  50440. this._buffer.update(this._vertexData);
  50441. // Render
  50442. var effect = this._effectBase;
  50443. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50444. effect = this._effectFog;
  50445. }
  50446. engine.enableEffect(effect);
  50447. var viewMatrix = this._scene.getViewMatrix();
  50448. effect.setTexture("diffuseSampler", this._spriteTexture);
  50449. effect.setMatrix("view", viewMatrix);
  50450. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50451. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50452. // Fog
  50453. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50454. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50455. effect.setColor3("vFogColor", this._scene.fogColor);
  50456. }
  50457. // VBOs
  50458. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50459. // Draw order
  50460. engine.setDepthFunctionToLessOrEqual();
  50461. effect.setBool("alphaTest", true);
  50462. engine.setColorWrite(false);
  50463. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50464. engine.setColorWrite(true);
  50465. effect.setBool("alphaTest", false);
  50466. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50467. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50468. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50469. };
  50470. SpriteManager.prototype.dispose = function () {
  50471. if (this._buffer) {
  50472. this._buffer.dispose();
  50473. this._buffer = null;
  50474. }
  50475. if (this._indexBuffer) {
  50476. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50477. this._indexBuffer = null;
  50478. }
  50479. if (this._spriteTexture) {
  50480. this._spriteTexture.dispose();
  50481. this._spriteTexture = null;
  50482. }
  50483. // Remove from scene
  50484. var index = this._scene.spriteManagers.indexOf(this);
  50485. this._scene.spriteManagers.splice(index, 1);
  50486. // Callback
  50487. this.onDisposeObservable.notifyObservers(this);
  50488. this.onDisposeObservable.clear();
  50489. };
  50490. return SpriteManager;
  50491. }());
  50492. BABYLON.SpriteManager = SpriteManager;
  50493. })(BABYLON || (BABYLON = {}));
  50494. //# sourceMappingURL=babylon.spriteManager.js.map
  50495. "use strict";
  50496. var BABYLON;
  50497. (function (BABYLON) {
  50498. var Sprite = /** @class */ (function () {
  50499. function Sprite(name, manager) {
  50500. this.name = name;
  50501. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50502. this.width = 1.0;
  50503. this.height = 1.0;
  50504. this.angle = 0;
  50505. this.cellIndex = 0;
  50506. this.invertU = 0;
  50507. this.invertV = 0;
  50508. this.animations = new Array();
  50509. this.isPickable = false;
  50510. this._animationStarted = false;
  50511. this._loopAnimation = false;
  50512. this._fromIndex = 0;
  50513. this._toIndex = 0;
  50514. this._delay = 0;
  50515. this._direction = 1;
  50516. this._time = 0;
  50517. this._manager = manager;
  50518. this._manager.sprites.push(this);
  50519. this.position = BABYLON.Vector3.Zero();
  50520. }
  50521. Object.defineProperty(Sprite.prototype, "size", {
  50522. get: function () {
  50523. return this.width;
  50524. },
  50525. set: function (value) {
  50526. this.width = value;
  50527. this.height = value;
  50528. },
  50529. enumerable: true,
  50530. configurable: true
  50531. });
  50532. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50533. this._fromIndex = from;
  50534. this._toIndex = to;
  50535. this._loopAnimation = loop;
  50536. this._delay = delay;
  50537. this._animationStarted = true;
  50538. this._direction = from < to ? 1 : -1;
  50539. this.cellIndex = from;
  50540. this._time = 0;
  50541. this._onAnimationEnd = onAnimationEnd;
  50542. };
  50543. Sprite.prototype.stopAnimation = function () {
  50544. this._animationStarted = false;
  50545. };
  50546. Sprite.prototype._animate = function (deltaTime) {
  50547. if (!this._animationStarted)
  50548. return;
  50549. this._time += deltaTime;
  50550. if (this._time > this._delay) {
  50551. this._time = this._time % this._delay;
  50552. this.cellIndex += this._direction;
  50553. if (this.cellIndex > this._toIndex) {
  50554. if (this._loopAnimation) {
  50555. this.cellIndex = this._fromIndex;
  50556. }
  50557. else {
  50558. this.cellIndex = this._toIndex;
  50559. this._animationStarted = false;
  50560. if (this._onAnimationEnd) {
  50561. this._onAnimationEnd();
  50562. }
  50563. if (this.disposeWhenFinishedAnimating) {
  50564. this.dispose();
  50565. }
  50566. }
  50567. }
  50568. }
  50569. };
  50570. Sprite.prototype.dispose = function () {
  50571. for (var i = 0; i < this._manager.sprites.length; i++) {
  50572. if (this._manager.sprites[i] == this) {
  50573. this._manager.sprites.splice(i, 1);
  50574. }
  50575. }
  50576. };
  50577. return Sprite;
  50578. }());
  50579. BABYLON.Sprite = Sprite;
  50580. })(BABYLON || (BABYLON = {}));
  50581. //# sourceMappingURL=babylon.sprite.js.map
  50582. "use strict";
  50583. var BABYLON;
  50584. (function (BABYLON) {
  50585. var IntersectionInfo = /** @class */ (function () {
  50586. function IntersectionInfo(bu, bv, distance) {
  50587. this.bu = bu;
  50588. this.bv = bv;
  50589. this.distance = distance;
  50590. this.faceId = 0;
  50591. this.subMeshId = 0;
  50592. }
  50593. return IntersectionInfo;
  50594. }());
  50595. BABYLON.IntersectionInfo = IntersectionInfo;
  50596. var PickingInfo = /** @class */ (function () {
  50597. function PickingInfo() {
  50598. this.hit = false;
  50599. this.distance = 0;
  50600. this.pickedPoint = null;
  50601. this.pickedMesh = null;
  50602. this.bu = 0;
  50603. this.bv = 0;
  50604. this.faceId = -1;
  50605. this.subMeshId = 0;
  50606. this.pickedSprite = null;
  50607. }
  50608. // Methods
  50609. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50610. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50611. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50612. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50613. return null;
  50614. }
  50615. var indices = this.pickedMesh.getIndices();
  50616. if (!indices) {
  50617. return null;
  50618. }
  50619. var result;
  50620. if (useVerticesNormals) {
  50621. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50622. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50623. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50624. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50625. normal0 = normal0.scale(this.bu);
  50626. normal1 = normal1.scale(this.bv);
  50627. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50628. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50629. }
  50630. else {
  50631. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50632. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50633. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50634. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50635. var p1p2 = vertex1.subtract(vertex2);
  50636. var p3p2 = vertex3.subtract(vertex2);
  50637. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50638. }
  50639. if (useWorldCoordinates) {
  50640. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50641. }
  50642. return BABYLON.Vector3.Normalize(result);
  50643. };
  50644. PickingInfo.prototype.getTextureCoordinates = function () {
  50645. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50646. return null;
  50647. }
  50648. var indices = this.pickedMesh.getIndices();
  50649. if (!indices) {
  50650. return null;
  50651. }
  50652. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50653. if (!uvs) {
  50654. return null;
  50655. }
  50656. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50657. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50658. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50659. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50660. uv1 = uv1.scale(this.bu);
  50661. uv2 = uv2.scale(this.bv);
  50662. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50663. };
  50664. return PickingInfo;
  50665. }());
  50666. BABYLON.PickingInfo = PickingInfo;
  50667. })(BABYLON || (BABYLON = {}));
  50668. //# sourceMappingURL=babylon.pickingInfo.js.map
  50669. "use strict";
  50670. var BABYLON;
  50671. (function (BABYLON) {
  50672. var Ray = /** @class */ (function () {
  50673. function Ray(origin, direction, length) {
  50674. if (length === void 0) { length = Number.MAX_VALUE; }
  50675. this.origin = origin;
  50676. this.direction = direction;
  50677. this.length = length;
  50678. }
  50679. // Methods
  50680. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50681. var d = 0.0;
  50682. var maxValue = Number.MAX_VALUE;
  50683. var inv;
  50684. var min;
  50685. var max;
  50686. var temp;
  50687. if (Math.abs(this.direction.x) < 0.0000001) {
  50688. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50689. return false;
  50690. }
  50691. }
  50692. else {
  50693. inv = 1.0 / this.direction.x;
  50694. min = (minimum.x - this.origin.x) * inv;
  50695. max = (maximum.x - this.origin.x) * inv;
  50696. if (max === -Infinity) {
  50697. max = Infinity;
  50698. }
  50699. if (min > max) {
  50700. temp = min;
  50701. min = max;
  50702. max = temp;
  50703. }
  50704. d = Math.max(min, d);
  50705. maxValue = Math.min(max, maxValue);
  50706. if (d > maxValue) {
  50707. return false;
  50708. }
  50709. }
  50710. if (Math.abs(this.direction.y) < 0.0000001) {
  50711. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50712. return false;
  50713. }
  50714. }
  50715. else {
  50716. inv = 1.0 / this.direction.y;
  50717. min = (minimum.y - this.origin.y) * inv;
  50718. max = (maximum.y - this.origin.y) * inv;
  50719. if (max === -Infinity) {
  50720. max = Infinity;
  50721. }
  50722. if (min > max) {
  50723. temp = min;
  50724. min = max;
  50725. max = temp;
  50726. }
  50727. d = Math.max(min, d);
  50728. maxValue = Math.min(max, maxValue);
  50729. if (d > maxValue) {
  50730. return false;
  50731. }
  50732. }
  50733. if (Math.abs(this.direction.z) < 0.0000001) {
  50734. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50735. return false;
  50736. }
  50737. }
  50738. else {
  50739. inv = 1.0 / this.direction.z;
  50740. min = (minimum.z - this.origin.z) * inv;
  50741. max = (maximum.z - this.origin.z) * inv;
  50742. if (max === -Infinity) {
  50743. max = Infinity;
  50744. }
  50745. if (min > max) {
  50746. temp = min;
  50747. min = max;
  50748. max = temp;
  50749. }
  50750. d = Math.max(min, d);
  50751. maxValue = Math.min(max, maxValue);
  50752. if (d > maxValue) {
  50753. return false;
  50754. }
  50755. }
  50756. return true;
  50757. };
  50758. Ray.prototype.intersectsBox = function (box) {
  50759. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50760. };
  50761. Ray.prototype.intersectsSphere = function (sphere) {
  50762. var x = sphere.center.x - this.origin.x;
  50763. var y = sphere.center.y - this.origin.y;
  50764. var z = sphere.center.z - this.origin.z;
  50765. var pyth = (x * x) + (y * y) + (z * z);
  50766. var rr = sphere.radius * sphere.radius;
  50767. if (pyth <= rr) {
  50768. return true;
  50769. }
  50770. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50771. if (dot < 0.0) {
  50772. return false;
  50773. }
  50774. var temp = pyth - (dot * dot);
  50775. return temp <= rr;
  50776. };
  50777. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50778. if (!this._edge1) {
  50779. this._edge1 = BABYLON.Vector3.Zero();
  50780. this._edge2 = BABYLON.Vector3.Zero();
  50781. this._pvec = BABYLON.Vector3.Zero();
  50782. this._tvec = BABYLON.Vector3.Zero();
  50783. this._qvec = BABYLON.Vector3.Zero();
  50784. }
  50785. vertex1.subtractToRef(vertex0, this._edge1);
  50786. vertex2.subtractToRef(vertex0, this._edge2);
  50787. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50788. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50789. if (det === 0) {
  50790. return null;
  50791. }
  50792. var invdet = 1 / det;
  50793. this.origin.subtractToRef(vertex0, this._tvec);
  50794. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50795. if (bu < 0 || bu > 1.0) {
  50796. return null;
  50797. }
  50798. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50799. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50800. if (bv < 0 || bu + bv > 1.0) {
  50801. return null;
  50802. }
  50803. //check if the distance is longer than the predefined length.
  50804. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50805. if (distance > this.length) {
  50806. return null;
  50807. }
  50808. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50809. };
  50810. Ray.prototype.intersectsPlane = function (plane) {
  50811. var distance;
  50812. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50813. if (Math.abs(result1) < 9.99999997475243E-07) {
  50814. return null;
  50815. }
  50816. else {
  50817. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50818. distance = (-plane.d - result2) / result1;
  50819. if (distance < 0.0) {
  50820. if (distance < -9.99999997475243E-07) {
  50821. return null;
  50822. }
  50823. else {
  50824. return 0;
  50825. }
  50826. }
  50827. return distance;
  50828. }
  50829. };
  50830. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50831. var tm = BABYLON.Tmp.Matrix[0];
  50832. mesh.getWorldMatrix().invertToRef(tm);
  50833. if (this._tmpRay) {
  50834. Ray.TransformToRef(this, tm, this._tmpRay);
  50835. }
  50836. else {
  50837. this._tmpRay = Ray.Transform(this, tm);
  50838. }
  50839. return mesh.intersects(this._tmpRay, fastCheck);
  50840. };
  50841. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50842. if (results) {
  50843. results.length = 0;
  50844. }
  50845. else {
  50846. results = [];
  50847. }
  50848. for (var i = 0; i < meshes.length; i++) {
  50849. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50850. if (pickInfo.hit) {
  50851. results.push(pickInfo);
  50852. }
  50853. }
  50854. results.sort(this._comparePickingInfo);
  50855. return results;
  50856. };
  50857. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50858. if (pickingInfoA.distance < pickingInfoB.distance) {
  50859. return -1;
  50860. }
  50861. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50862. return 1;
  50863. }
  50864. else {
  50865. return 0;
  50866. }
  50867. };
  50868. /**
  50869. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50870. * @param sega the first point of the segment to test the intersection against
  50871. * @param segb the second point of the segment to test the intersection against
  50872. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50873. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50874. */
  50875. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50876. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50877. var u = segb.subtract(sega);
  50878. var v = rsegb.subtract(this.origin);
  50879. var w = sega.subtract(this.origin);
  50880. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50881. var b = BABYLON.Vector3.Dot(u, v);
  50882. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50883. var d = BABYLON.Vector3.Dot(u, w);
  50884. var e = BABYLON.Vector3.Dot(v, w);
  50885. var D = a * c - b * b; // always >= 0
  50886. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50887. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50888. // compute the line parameters of the two closest points
  50889. if (D < Ray.smallnum) {
  50890. sN = 0.0; // force using point P0 on segment S1
  50891. sD = 1.0; // to prevent possible division by 0.0 later
  50892. tN = e;
  50893. tD = c;
  50894. }
  50895. else {
  50896. sN = (b * e - c * d);
  50897. tN = (a * e - b * d);
  50898. if (sN < 0.0) {
  50899. sN = 0.0;
  50900. tN = e;
  50901. tD = c;
  50902. }
  50903. else if (sN > sD) {
  50904. sN = sD;
  50905. tN = e + b;
  50906. tD = c;
  50907. }
  50908. }
  50909. if (tN < 0.0) {
  50910. tN = 0.0;
  50911. // recompute sc for this edge
  50912. if (-d < 0.0) {
  50913. sN = 0.0;
  50914. }
  50915. else if (-d > a)
  50916. sN = sD;
  50917. else {
  50918. sN = -d;
  50919. sD = a;
  50920. }
  50921. }
  50922. else if (tN > tD) {
  50923. tN = tD;
  50924. // recompute sc for this edge
  50925. if ((-d + b) < 0.0) {
  50926. sN = 0;
  50927. }
  50928. else if ((-d + b) > a) {
  50929. sN = sD;
  50930. }
  50931. else {
  50932. sN = (-d + b);
  50933. sD = a;
  50934. }
  50935. }
  50936. // finally do the division to get sc and tc
  50937. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50938. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50939. // get the difference of the two closest points
  50940. var qtc = v.multiplyByFloats(tc, tc, tc);
  50941. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50942. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50943. if (isIntersected) {
  50944. return qtc.length();
  50945. }
  50946. return -1;
  50947. };
  50948. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50949. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50950. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50951. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50952. this.direction.normalize();
  50953. return this;
  50954. };
  50955. // Statics
  50956. Ray.Zero = function () {
  50957. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50958. };
  50959. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50960. var result = Ray.Zero();
  50961. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50962. };
  50963. /**
  50964. * 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
  50965. * transformed to the given world matrix.
  50966. * @param origin The origin point
  50967. * @param end The end point
  50968. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50969. */
  50970. Ray.CreateNewFromTo = function (origin, end, world) {
  50971. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50972. var direction = end.subtract(origin);
  50973. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50974. direction.normalize();
  50975. return Ray.Transform(new Ray(origin, direction, length), world);
  50976. };
  50977. Ray.Transform = function (ray, matrix) {
  50978. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50979. Ray.TransformToRef(ray, matrix, result);
  50980. return result;
  50981. };
  50982. Ray.TransformToRef = function (ray, matrix, result) {
  50983. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50984. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50985. result.length = ray.length;
  50986. var dir = result.direction;
  50987. var len = dir.length();
  50988. if (!(len === 0 || len === 1)) {
  50989. var num = 1.0 / len;
  50990. dir.x *= num;
  50991. dir.y *= num;
  50992. dir.z *= num;
  50993. result.length *= len;
  50994. }
  50995. };
  50996. Ray.smallnum = 0.00000001;
  50997. Ray.rayl = 10e8;
  50998. return Ray;
  50999. }());
  51000. BABYLON.Ray = Ray;
  51001. })(BABYLON || (BABYLON = {}));
  51002. //# sourceMappingURL=babylon.ray.js.map
  51003. "use strict";
  51004. var BABYLON;
  51005. (function (BABYLON) {
  51006. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  51007. if (boxMin.x > sphereCenter.x + sphereRadius)
  51008. return false;
  51009. if (sphereCenter.x - sphereRadius > boxMax.x)
  51010. return false;
  51011. if (boxMin.y > sphereCenter.y + sphereRadius)
  51012. return false;
  51013. if (sphereCenter.y - sphereRadius > boxMax.y)
  51014. return false;
  51015. if (boxMin.z > sphereCenter.z + sphereRadius)
  51016. return false;
  51017. if (sphereCenter.z - sphereRadius > boxMax.z)
  51018. return false;
  51019. return true;
  51020. };
  51021. var getLowestRoot = (function () {
  51022. var result = { root: 0, found: false };
  51023. return function (a, b, c, maxR) {
  51024. result.root = 0;
  51025. result.found = false;
  51026. var determinant = b * b - 4.0 * a * c;
  51027. if (determinant < 0)
  51028. return result;
  51029. var sqrtD = Math.sqrt(determinant);
  51030. var r1 = (-b - sqrtD) / (2.0 * a);
  51031. var r2 = (-b + sqrtD) / (2.0 * a);
  51032. if (r1 > r2) {
  51033. var temp = r2;
  51034. r2 = r1;
  51035. r1 = temp;
  51036. }
  51037. if (r1 > 0 && r1 < maxR) {
  51038. result.root = r1;
  51039. result.found = true;
  51040. return result;
  51041. }
  51042. if (r2 > 0 && r2 < maxR) {
  51043. result.root = r2;
  51044. result.found = true;
  51045. return result;
  51046. }
  51047. return result;
  51048. };
  51049. })();
  51050. var Collider = /** @class */ (function () {
  51051. function Collider() {
  51052. this._collisionPoint = BABYLON.Vector3.Zero();
  51053. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  51054. this._tempVector = BABYLON.Vector3.Zero();
  51055. this._tempVector2 = BABYLON.Vector3.Zero();
  51056. this._tempVector3 = BABYLON.Vector3.Zero();
  51057. this._tempVector4 = BABYLON.Vector3.Zero();
  51058. this._edge = BABYLON.Vector3.Zero();
  51059. this._baseToVertex = BABYLON.Vector3.Zero();
  51060. this._destinationPoint = BABYLON.Vector3.Zero();
  51061. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51062. this._displacementVector = BABYLON.Vector3.Zero();
  51063. this._radius = BABYLON.Vector3.One();
  51064. this._retry = 0;
  51065. this._basePointWorld = BABYLON.Vector3.Zero();
  51066. this._velocityWorld = BABYLON.Vector3.Zero();
  51067. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51068. this._collisionMask = -1;
  51069. }
  51070. Object.defineProperty(Collider.prototype, "collisionMask", {
  51071. get: function () {
  51072. return this._collisionMask;
  51073. },
  51074. set: function (mask) {
  51075. this._collisionMask = !isNaN(mask) ? mask : -1;
  51076. },
  51077. enumerable: true,
  51078. configurable: true
  51079. });
  51080. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51081. /**
  51082. * Gets the plane normal used to compute the sliding response (in local space)
  51083. */
  51084. get: function () {
  51085. return this._slidePlaneNormal;
  51086. },
  51087. enumerable: true,
  51088. configurable: true
  51089. });
  51090. // Methods
  51091. Collider.prototype._initialize = function (source, dir, e) {
  51092. this._velocity = dir;
  51093. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51094. this._basePoint = source;
  51095. source.multiplyToRef(this._radius, this._basePointWorld);
  51096. dir.multiplyToRef(this._radius, this._velocityWorld);
  51097. this._velocityWorldLength = this._velocityWorld.length();
  51098. this._epsilon = e;
  51099. this.collisionFound = false;
  51100. };
  51101. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51102. pa.subtractToRef(point, this._tempVector);
  51103. pb.subtractToRef(point, this._tempVector2);
  51104. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51105. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51106. if (d < 0)
  51107. return false;
  51108. pc.subtractToRef(point, this._tempVector3);
  51109. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51110. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51111. if (d < 0)
  51112. return false;
  51113. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51114. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51115. return d >= 0;
  51116. };
  51117. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51118. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51119. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51120. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51121. return false;
  51122. }
  51123. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51124. return false;
  51125. return true;
  51126. };
  51127. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51128. var t0;
  51129. var embeddedInPlane = false;
  51130. //defensive programming, actually not needed.
  51131. if (!trianglePlaneArray) {
  51132. trianglePlaneArray = [];
  51133. }
  51134. if (!trianglePlaneArray[faceIndex]) {
  51135. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51136. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51137. }
  51138. var trianglePlane = trianglePlaneArray[faceIndex];
  51139. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51140. return;
  51141. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51142. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51143. if (normalDotVelocity == 0) {
  51144. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51145. return;
  51146. embeddedInPlane = true;
  51147. t0 = 0;
  51148. }
  51149. else {
  51150. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51151. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51152. if (t0 > t1) {
  51153. var temp = t1;
  51154. t1 = t0;
  51155. t0 = temp;
  51156. }
  51157. if (t0 > 1.0 || t1 < 0.0)
  51158. return;
  51159. if (t0 < 0)
  51160. t0 = 0;
  51161. if (t0 > 1.0)
  51162. t0 = 1.0;
  51163. }
  51164. this._collisionPoint.copyFromFloats(0, 0, 0);
  51165. var found = false;
  51166. var t = 1.0;
  51167. if (!embeddedInPlane) {
  51168. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51169. this._velocity.scaleToRef(t0, this._tempVector);
  51170. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51171. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51172. found = true;
  51173. t = t0;
  51174. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51175. }
  51176. }
  51177. if (!found) {
  51178. var velocitySquaredLength = this._velocity.lengthSquared();
  51179. var a = velocitySquaredLength;
  51180. this._basePoint.subtractToRef(p1, this._tempVector);
  51181. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51182. var c = this._tempVector.lengthSquared() - 1.0;
  51183. var lowestRoot = getLowestRoot(a, b, c, t);
  51184. if (lowestRoot.found) {
  51185. t = lowestRoot.root;
  51186. found = true;
  51187. this._collisionPoint.copyFrom(p1);
  51188. }
  51189. this._basePoint.subtractToRef(p2, this._tempVector);
  51190. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51191. c = this._tempVector.lengthSquared() - 1.0;
  51192. lowestRoot = getLowestRoot(a, b, c, t);
  51193. if (lowestRoot.found) {
  51194. t = lowestRoot.root;
  51195. found = true;
  51196. this._collisionPoint.copyFrom(p2);
  51197. }
  51198. this._basePoint.subtractToRef(p3, this._tempVector);
  51199. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51200. c = this._tempVector.lengthSquared() - 1.0;
  51201. lowestRoot = getLowestRoot(a, b, c, t);
  51202. if (lowestRoot.found) {
  51203. t = lowestRoot.root;
  51204. found = true;
  51205. this._collisionPoint.copyFrom(p3);
  51206. }
  51207. p2.subtractToRef(p1, this._edge);
  51208. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51209. var edgeSquaredLength = this._edge.lengthSquared();
  51210. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51211. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51212. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51213. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51214. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51215. lowestRoot = getLowestRoot(a, b, c, t);
  51216. if (lowestRoot.found) {
  51217. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51218. if (f >= 0.0 && f <= 1.0) {
  51219. t = lowestRoot.root;
  51220. found = true;
  51221. this._edge.scaleInPlace(f);
  51222. p1.addToRef(this._edge, this._collisionPoint);
  51223. }
  51224. }
  51225. p3.subtractToRef(p2, this._edge);
  51226. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51227. edgeSquaredLength = this._edge.lengthSquared();
  51228. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51229. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51230. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51231. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51232. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51233. lowestRoot = getLowestRoot(a, b, c, t);
  51234. if (lowestRoot.found) {
  51235. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51236. if (f >= 0.0 && f <= 1.0) {
  51237. t = lowestRoot.root;
  51238. found = true;
  51239. this._edge.scaleInPlace(f);
  51240. p2.addToRef(this._edge, this._collisionPoint);
  51241. }
  51242. }
  51243. p1.subtractToRef(p3, this._edge);
  51244. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51245. edgeSquaredLength = this._edge.lengthSquared();
  51246. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51247. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51248. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51249. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51250. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51251. lowestRoot = getLowestRoot(a, b, c, t);
  51252. if (lowestRoot.found) {
  51253. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51254. if (f >= 0.0 && f <= 1.0) {
  51255. t = lowestRoot.root;
  51256. found = true;
  51257. this._edge.scaleInPlace(f);
  51258. p3.addToRef(this._edge, this._collisionPoint);
  51259. }
  51260. }
  51261. }
  51262. if (found) {
  51263. var distToCollision = t * this._velocity.length();
  51264. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51265. if (!this.intersectionPoint) {
  51266. this.intersectionPoint = this._collisionPoint.clone();
  51267. }
  51268. else {
  51269. this.intersectionPoint.copyFrom(this._collisionPoint);
  51270. }
  51271. this._nearestDistance = distToCollision;
  51272. this.collisionFound = true;
  51273. }
  51274. }
  51275. };
  51276. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51277. for (var i = indexStart; i < indexEnd; i += 3) {
  51278. var p1 = pts[indices[i] - decal];
  51279. var p2 = pts[indices[i + 1] - decal];
  51280. var p3 = pts[indices[i + 2] - decal];
  51281. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51282. }
  51283. };
  51284. Collider.prototype._getResponse = function (pos, vel) {
  51285. pos.addToRef(vel, this._destinationPoint);
  51286. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51287. this._basePoint.addToRef(vel, pos);
  51288. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51289. this._slidePlaneNormal.normalize();
  51290. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51291. pos.addInPlace(this._displacementVector);
  51292. this.intersectionPoint.addInPlace(this._displacementVector);
  51293. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51294. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51295. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51296. };
  51297. return Collider;
  51298. }());
  51299. BABYLON.Collider = Collider;
  51300. })(BABYLON || (BABYLON = {}));
  51301. //# sourceMappingURL=babylon.collider.js.map
  51302. "use strict";
  51303. var BABYLON;
  51304. (function (BABYLON) {
  51305. //WebWorker code will be inserted to this variable.
  51306. BABYLON.CollisionWorker = "";
  51307. var WorkerTaskType;
  51308. (function (WorkerTaskType) {
  51309. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51310. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51311. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51312. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51313. var WorkerReplyType;
  51314. (function (WorkerReplyType) {
  51315. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51316. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51317. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51318. var CollisionCoordinatorWorker = /** @class */ (function () {
  51319. function CollisionCoordinatorWorker() {
  51320. var _this = this;
  51321. this._scaledPosition = BABYLON.Vector3.Zero();
  51322. this._scaledVelocity = BABYLON.Vector3.Zero();
  51323. this.onMeshUpdated = function (transformNode) {
  51324. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51325. };
  51326. this.onGeometryUpdated = function (geometry) {
  51327. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51328. };
  51329. this._afterRender = function () {
  51330. if (!_this._init)
  51331. return;
  51332. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51333. return;
  51334. }
  51335. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51336. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51337. if (_this._runningUpdated > 4) {
  51338. return;
  51339. }
  51340. ++_this._runningUpdated;
  51341. var payload = {
  51342. updatedMeshes: _this._addUpdateMeshesList,
  51343. updatedGeometries: _this._addUpdateGeometriesList,
  51344. removedGeometries: _this._toRemoveGeometryArray,
  51345. removedMeshes: _this._toRemoveMeshesArray
  51346. };
  51347. var message = {
  51348. payload: payload,
  51349. taskType: WorkerTaskType.UPDATE
  51350. };
  51351. var serializable = [];
  51352. for (var id in payload.updatedGeometries) {
  51353. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51354. //prepare transferables
  51355. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51356. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51357. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51358. }
  51359. }
  51360. _this._worker.postMessage(message, serializable);
  51361. _this._addUpdateMeshesList = {};
  51362. _this._addUpdateGeometriesList = {};
  51363. _this._toRemoveGeometryArray = [];
  51364. _this._toRemoveMeshesArray = [];
  51365. };
  51366. this._onMessageFromWorker = function (e) {
  51367. var returnData = e.data;
  51368. if (returnData.error != WorkerReplyType.SUCCESS) {
  51369. //TODO what errors can be returned from the worker?
  51370. BABYLON.Tools.Warn("error returned from worker!");
  51371. return;
  51372. }
  51373. switch (returnData.taskType) {
  51374. case WorkerTaskType.INIT:
  51375. _this._init = true;
  51376. //Update the worked with ALL of the scene's current state
  51377. _this._scene.meshes.forEach(function (mesh) {
  51378. _this.onMeshAdded(mesh);
  51379. });
  51380. _this._scene.getGeometries().forEach(function (geometry) {
  51381. _this.onGeometryAdded(geometry);
  51382. });
  51383. break;
  51384. case WorkerTaskType.UPDATE:
  51385. _this._runningUpdated--;
  51386. break;
  51387. case WorkerTaskType.COLLIDE:
  51388. var returnPayload = returnData.payload;
  51389. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51390. return;
  51391. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51392. if (callback) {
  51393. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51394. if (mesh) {
  51395. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51396. }
  51397. }
  51398. //cleanup
  51399. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51400. break;
  51401. }
  51402. };
  51403. this._collisionsCallbackArray = [];
  51404. this._init = false;
  51405. this._runningUpdated = 0;
  51406. this._addUpdateMeshesList = {};
  51407. this._addUpdateGeometriesList = {};
  51408. this._toRemoveGeometryArray = [];
  51409. this._toRemoveMeshesArray = [];
  51410. }
  51411. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51412. if (!this._init)
  51413. return;
  51414. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51415. return;
  51416. position.divideToRef(collider._radius, this._scaledPosition);
  51417. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51418. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51419. var payload = {
  51420. collider: {
  51421. position: this._scaledPosition.asArray(),
  51422. velocity: this._scaledVelocity.asArray(),
  51423. radius: collider._radius.asArray()
  51424. },
  51425. collisionId: collisionIndex,
  51426. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51427. maximumRetry: maximumRetry
  51428. };
  51429. var message = {
  51430. payload: payload,
  51431. taskType: WorkerTaskType.COLLIDE
  51432. };
  51433. this._worker.postMessage(message);
  51434. };
  51435. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51436. this._scene = scene;
  51437. this._scene.registerAfterRender(this._afterRender);
  51438. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51439. this._worker = new Worker(workerUrl);
  51440. this._worker.onmessage = this._onMessageFromWorker;
  51441. var message = {
  51442. payload: {},
  51443. taskType: WorkerTaskType.INIT
  51444. };
  51445. this._worker.postMessage(message);
  51446. };
  51447. CollisionCoordinatorWorker.prototype.destroy = function () {
  51448. this._scene.unregisterAfterRender(this._afterRender);
  51449. this._worker.terminate();
  51450. };
  51451. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51452. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51453. this.onMeshUpdated(mesh);
  51454. };
  51455. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51456. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51457. };
  51458. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51459. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51460. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51461. this.onGeometryUpdated(geometry);
  51462. };
  51463. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51464. this._toRemoveGeometryArray.push(geometry.id);
  51465. };
  51466. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51467. var submeshes = [];
  51468. if (mesh.subMeshes) {
  51469. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51470. var boundingInfo = sm.getBoundingInfo();
  51471. return {
  51472. position: idx,
  51473. verticesStart: sm.verticesStart,
  51474. verticesCount: sm.verticesCount,
  51475. indexStart: sm.indexStart,
  51476. indexCount: sm.indexCount,
  51477. hasMaterial: !!sm.getMaterial(),
  51478. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51479. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51480. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51481. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51482. };
  51483. });
  51484. }
  51485. var geometryId = null;
  51486. if (mesh instanceof BABYLON.Mesh) {
  51487. var geometry = mesh.geometry;
  51488. geometryId = geometry ? geometry.id : null;
  51489. }
  51490. else if (mesh instanceof BABYLON.InstancedMesh) {
  51491. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51492. geometryId = geometry ? geometry.id : null;
  51493. }
  51494. var boundingInfo = mesh.getBoundingInfo();
  51495. return {
  51496. uniqueId: mesh.uniqueId,
  51497. id: mesh.id,
  51498. name: mesh.name,
  51499. geometryId: geometryId,
  51500. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51501. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51502. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51503. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51504. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51505. subMeshes: submeshes,
  51506. checkCollisions: mesh.checkCollisions
  51507. };
  51508. };
  51509. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51510. return {
  51511. id: geometry.id,
  51512. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51513. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51514. indices: new Uint32Array(geometry.getIndices() || []),
  51515. };
  51516. };
  51517. return CollisionCoordinatorWorker;
  51518. }());
  51519. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51520. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51521. function CollisionCoordinatorLegacy() {
  51522. this._scaledPosition = BABYLON.Vector3.Zero();
  51523. this._scaledVelocity = BABYLON.Vector3.Zero();
  51524. this._finalPosition = BABYLON.Vector3.Zero();
  51525. }
  51526. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51527. position.divideToRef(collider._radius, this._scaledPosition);
  51528. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51529. collider.collidedMesh = null;
  51530. collider._retry = 0;
  51531. collider._initialVelocity = this._scaledVelocity;
  51532. collider._initialPosition = this._scaledPosition;
  51533. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51534. this._finalPosition.multiplyInPlace(collider._radius);
  51535. //run the callback
  51536. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51537. };
  51538. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51539. this._scene = scene;
  51540. };
  51541. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51542. //Legacy need no destruction method.
  51543. };
  51544. //No update in legacy mode
  51545. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51546. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51547. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51548. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51549. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51550. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51551. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51552. if (excludedMesh === void 0) { excludedMesh = null; }
  51553. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51554. if (collider._retry >= maximumRetry) {
  51555. finalPosition.copyFrom(position);
  51556. return;
  51557. }
  51558. // Check if this is a mesh else camera or -1
  51559. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51560. collider._initialize(position, velocity, closeDistance);
  51561. // Check all meshes
  51562. for (var index = 0; index < this._scene.meshes.length; index++) {
  51563. var mesh = this._scene.meshes[index];
  51564. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51565. mesh._checkCollision(collider);
  51566. }
  51567. }
  51568. if (!collider.collisionFound) {
  51569. position.addToRef(velocity, finalPosition);
  51570. return;
  51571. }
  51572. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51573. collider._getResponse(position, velocity);
  51574. }
  51575. if (velocity.length() <= closeDistance) {
  51576. finalPosition.copyFrom(position);
  51577. return;
  51578. }
  51579. collider._retry++;
  51580. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51581. };
  51582. return CollisionCoordinatorLegacy;
  51583. }());
  51584. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51585. })(BABYLON || (BABYLON = {}));
  51586. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51587. "use strict";
  51588. var BABYLON;
  51589. (function (BABYLON) {
  51590. /**
  51591. * A particle represents one of the element emitted by a particle system.
  51592. * This is mainly define by its coordinates, direction, velocity and age.
  51593. */
  51594. var Particle = /** @class */ (function () {
  51595. /**
  51596. * Creates a new instance Particle
  51597. * @param particleSystem the particle system the particle belongs to
  51598. */
  51599. function Particle(
  51600. /**
  51601. * particleSystem the particle system the particle belongs to.
  51602. */
  51603. particleSystem) {
  51604. this.particleSystem = particleSystem;
  51605. /**
  51606. * The world position of the particle in the scene.
  51607. */
  51608. this.position = BABYLON.Vector3.Zero();
  51609. /**
  51610. * The world direction of the particle in the scene.
  51611. */
  51612. this.direction = BABYLON.Vector3.Zero();
  51613. /**
  51614. * The color of the particle.
  51615. */
  51616. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51617. /**
  51618. * The color change of the particle per step.
  51619. */
  51620. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51621. /**
  51622. * Defines how long will the life of the particle be.
  51623. */
  51624. this.lifeTime = 1.0;
  51625. /**
  51626. * The current age of the particle.
  51627. */
  51628. this.age = 0;
  51629. /**
  51630. * The current size of the particle.
  51631. */
  51632. this.size = 0;
  51633. /**
  51634. * The current angle of the particle.
  51635. */
  51636. this.angle = 0;
  51637. /**
  51638. * Defines how fast is the angle changing.
  51639. */
  51640. this.angularSpeed = 0;
  51641. /**
  51642. * Defines the cell index used by the particle to be rendered from a sprite.
  51643. */
  51644. this.cellIndex = 0;
  51645. this._currentFrameCounter = 0;
  51646. if (!this.particleSystem.isAnimationSheetEnabled) {
  51647. return;
  51648. }
  51649. this.updateCellInfoFromSystem();
  51650. }
  51651. Particle.prototype.updateCellInfoFromSystem = function () {
  51652. this.cellIndex = this.particleSystem.startSpriteCellID;
  51653. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51654. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51655. }
  51656. else {
  51657. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51658. }
  51659. };
  51660. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51661. // (ageOffset / scaledUpdateSpeed) / available cells
  51662. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51663. this._currentFrameCounter += scaledUpdateSpeed;
  51664. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51665. this._currentFrameCounter = 0;
  51666. this.cellIndex++;
  51667. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51668. this.cellIndex = this.particleSystem.endSpriteCellID;
  51669. }
  51670. }
  51671. };
  51672. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51673. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51674. this.cellIndex++;
  51675. this._currentFrameCounter = 0;
  51676. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51677. if (this.particleSystem.spriteCellLoop) {
  51678. this.cellIndex = this.particleSystem.startSpriteCellID;
  51679. }
  51680. else {
  51681. this.cellIndex = this.particleSystem.endSpriteCellID;
  51682. }
  51683. }
  51684. }
  51685. else {
  51686. this._currentFrameCounter++;
  51687. }
  51688. };
  51689. /**
  51690. * Copy the properties of particle to another one.
  51691. * @param other the particle to copy the information to.
  51692. */
  51693. Particle.prototype.copyTo = function (other) {
  51694. other.position.copyFrom(this.position);
  51695. other.direction.copyFrom(this.direction);
  51696. other.color.copyFrom(this.color);
  51697. other.colorStep.copyFrom(this.colorStep);
  51698. other.lifeTime = this.lifeTime;
  51699. other.age = this.age;
  51700. other.size = this.size;
  51701. other.angle = this.angle;
  51702. other.angularSpeed = this.angularSpeed;
  51703. other.particleSystem = this.particleSystem;
  51704. other.cellIndex = this.cellIndex;
  51705. };
  51706. return Particle;
  51707. }());
  51708. BABYLON.Particle = Particle;
  51709. })(BABYLON || (BABYLON = {}));
  51710. //# sourceMappingURL=babylon.particle.js.map
  51711. "use strict";
  51712. var BABYLON;
  51713. (function (BABYLON) {
  51714. /**
  51715. * This represents a particle system in Babylon.
  51716. * 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.
  51717. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51718. * @example https://doc.babylonjs.com/babylon101/particles
  51719. */
  51720. var ParticleSystem = /** @class */ (function () {
  51721. /**
  51722. * Instantiates a particle system.
  51723. * 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.
  51724. * @param name The name of the particle system
  51725. * @param capacity The max number of particles alive at the same time
  51726. * @param scene The scene the particle system belongs to
  51727. * @param customEffect a custom effect used to change the way particles are rendered by default
  51728. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51729. * @param epsilon Offset used to render the particles
  51730. */
  51731. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51732. if (customEffect === void 0) { customEffect = null; }
  51733. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51734. if (epsilon === void 0) { epsilon = 0.01; }
  51735. var _this = this;
  51736. /**
  51737. * List of animations used by the particle system.
  51738. */
  51739. this.animations = [];
  51740. /**
  51741. * The rendering group used by the Particle system to chose when to render.
  51742. */
  51743. this.renderingGroupId = 0;
  51744. /**
  51745. * The emitter represents the Mesh or position we are attaching the particle system to.
  51746. */
  51747. this.emitter = null;
  51748. /**
  51749. * The maximum number of particles to emit per frame
  51750. */
  51751. this.emitRate = 10;
  51752. /**
  51753. * If you want to launch only a few particles at once, that can be done, as well.
  51754. */
  51755. this.manualEmitCount = -1;
  51756. /**
  51757. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51758. */
  51759. this.updateSpeed = 0.01;
  51760. /**
  51761. * The amount of time the particle system is running (depends of the overall update speed).
  51762. */
  51763. this.targetStopDuration = 0;
  51764. /**
  51765. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51766. */
  51767. this.disposeOnStop = false;
  51768. /**
  51769. * Minimum power of emitting particles.
  51770. */
  51771. this.minEmitPower = 1;
  51772. /**
  51773. * Maximum power of emitting particles.
  51774. */
  51775. this.maxEmitPower = 1;
  51776. /**
  51777. * Minimum life time of emitting particles.
  51778. */
  51779. this.minLifeTime = 1;
  51780. /**
  51781. * Maximum life time of emitting particles.
  51782. */
  51783. this.maxLifeTime = 1;
  51784. /**
  51785. * Minimum Size of emitting particles.
  51786. */
  51787. this.minSize = 1;
  51788. /**
  51789. * Maximum Size of emitting particles.
  51790. */
  51791. this.maxSize = 1;
  51792. /**
  51793. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51794. */
  51795. this.minAngularSpeed = 0;
  51796. /**
  51797. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51798. */
  51799. this.maxAngularSpeed = 0;
  51800. /**
  51801. * The layer mask we are rendering the particles through.
  51802. */
  51803. this.layerMask = 0x0FFFFFFF;
  51804. /**
  51805. * This can help using your own shader to render the particle system.
  51806. * The according effect will be created
  51807. */
  51808. this.customShader = null;
  51809. /**
  51810. * By default particle system starts as soon as they are created. This prevents the
  51811. * automatic start to happen and let you decide when to start emitting particles.
  51812. */
  51813. this.preventAutoStart = false;
  51814. /**
  51815. * Callback triggered when the particle animation is ending.
  51816. */
  51817. this.onAnimationEnd = null;
  51818. /**
  51819. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51820. */
  51821. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51822. /**
  51823. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51824. * to override the particles.
  51825. */
  51826. this.forceDepthWrite = false;
  51827. /**
  51828. * You can use gravity if you want to give an orientation to your particles.
  51829. */
  51830. this.gravity = BABYLON.Vector3.Zero();
  51831. /**
  51832. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51833. */
  51834. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51835. /**
  51836. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51837. */
  51838. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51839. /**
  51840. * Color the particle will have at the end of its lifetime.
  51841. */
  51842. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51843. /**
  51844. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51845. */
  51846. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51847. /**
  51848. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51849. */
  51850. this.spriteCellLoop = true;
  51851. /**
  51852. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51853. */
  51854. this.spriteCellChangeSpeed = 0;
  51855. /**
  51856. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51857. */
  51858. this.startSpriteCellID = 0;
  51859. /**
  51860. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51861. */
  51862. this.endSpriteCellID = 0;
  51863. /**
  51864. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51865. */
  51866. this.spriteCellWidth = 0;
  51867. /**
  51868. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51869. */
  51870. this.spriteCellHeight = 0;
  51871. /**
  51872. * An event triggered when the system is disposed.
  51873. */
  51874. this.onDisposeObservable = new BABYLON.Observable();
  51875. this._particles = new Array();
  51876. this._stockParticles = new Array();
  51877. this._newPartsExcess = 0;
  51878. this._vertexBuffers = {};
  51879. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51880. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51881. this._scaledDirection = BABYLON.Vector3.Zero();
  51882. this._scaledGravity = BABYLON.Vector3.Zero();
  51883. this._currentRenderId = -1;
  51884. this._started = false;
  51885. this._stopped = false;
  51886. this._actualFrame = 0;
  51887. this._vertexBufferSize = 11;
  51888. // start of sub system methods
  51889. /**
  51890. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51891. * Its lifetime will start back at 0.
  51892. */
  51893. this.recycleParticle = function (particle) {
  51894. var lastParticle = _this._particles.pop();
  51895. if (lastParticle !== particle) {
  51896. lastParticle.copyTo(particle);
  51897. }
  51898. _this._stockParticles.push(lastParticle);
  51899. };
  51900. this._createParticle = function () {
  51901. var particle;
  51902. if (_this._stockParticles.length !== 0) {
  51903. particle = _this._stockParticles.pop();
  51904. particle.age = 0;
  51905. particle.cellIndex = _this.startSpriteCellID;
  51906. }
  51907. else {
  51908. particle = new BABYLON.Particle(_this);
  51909. }
  51910. return particle;
  51911. };
  51912. this._emitFromParticle = function (particle) {
  51913. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51914. return;
  51915. }
  51916. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51917. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51918. subSystem._rootParticleSystem = _this;
  51919. _this.activeSubSystems.push(subSystem);
  51920. subSystem.start();
  51921. };
  51922. this._appendParticleVertexes = null;
  51923. this.id = name;
  51924. this.name = name;
  51925. this._capacity = capacity;
  51926. this._epsilon = epsilon;
  51927. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51928. if (isAnimationSheetEnabled) {
  51929. this._vertexBufferSize = 12;
  51930. }
  51931. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51932. this._customEffect = customEffect;
  51933. scene.particleSystems.push(this);
  51934. this._createIndexBuffer();
  51935. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51936. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51937. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51938. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51939. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51940. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51941. if (this._isAnimationSheetEnabled) {
  51942. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51943. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51944. }
  51945. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51946. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51947. this._vertexBuffers["options"] = options;
  51948. // Default emitter type
  51949. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51950. this.updateFunction = function (particles) {
  51951. for (var index = 0; index < particles.length; index++) {
  51952. var particle = particles[index];
  51953. particle.age += _this._scaledUpdateSpeed;
  51954. if (particle.age >= particle.lifeTime) {
  51955. _this._emitFromParticle(particle);
  51956. _this.recycleParticle(particle);
  51957. index--;
  51958. continue;
  51959. }
  51960. else {
  51961. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51962. particle.color.addInPlace(_this._scaledColorStep);
  51963. if (particle.color.a < 0)
  51964. particle.color.a = 0;
  51965. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51966. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51967. particle.position.addInPlace(_this._scaledDirection);
  51968. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51969. particle.direction.addInPlace(_this._scaledGravity);
  51970. if (_this._isAnimationSheetEnabled) {
  51971. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51972. }
  51973. }
  51974. }
  51975. };
  51976. }
  51977. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51978. /**
  51979. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51980. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51981. */
  51982. get: function () {
  51983. if (this.particleEmitterType.direction1) {
  51984. return this.particleEmitterType.direction1;
  51985. }
  51986. return BABYLON.Vector3.Zero();
  51987. },
  51988. set: function (value) {
  51989. if (this.particleEmitterType.direction1) {
  51990. this.particleEmitterType.direction1 = value;
  51991. }
  51992. },
  51993. enumerable: true,
  51994. configurable: true
  51995. });
  51996. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51997. /**
  51998. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51999. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52000. */
  52001. get: function () {
  52002. if (this.particleEmitterType.direction2) {
  52003. return this.particleEmitterType.direction2;
  52004. }
  52005. return BABYLON.Vector3.Zero();
  52006. },
  52007. set: function (value) {
  52008. if (this.particleEmitterType.direction2) {
  52009. this.particleEmitterType.direction2 = value;
  52010. }
  52011. },
  52012. enumerable: true,
  52013. configurable: true
  52014. });
  52015. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  52016. /**
  52017. * 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.
  52018. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52019. */
  52020. get: function () {
  52021. if (this.particleEmitterType.minEmitBox) {
  52022. return this.particleEmitterType.minEmitBox;
  52023. }
  52024. return BABYLON.Vector3.Zero();
  52025. },
  52026. set: function (value) {
  52027. if (this.particleEmitterType.minEmitBox) {
  52028. this.particleEmitterType.minEmitBox = value;
  52029. }
  52030. },
  52031. enumerable: true,
  52032. configurable: true
  52033. });
  52034. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  52035. /**
  52036. * 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.
  52037. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52038. */
  52039. get: function () {
  52040. if (this.particleEmitterType.maxEmitBox) {
  52041. return this.particleEmitterType.maxEmitBox;
  52042. }
  52043. return BABYLON.Vector3.Zero();
  52044. },
  52045. set: function (value) {
  52046. if (this.particleEmitterType.maxEmitBox) {
  52047. this.particleEmitterType.maxEmitBox = value;
  52048. }
  52049. },
  52050. enumerable: true,
  52051. configurable: true
  52052. });
  52053. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  52054. /**
  52055. * Sets a callback that will be triggered when the system is disposed.
  52056. */
  52057. set: function (callback) {
  52058. if (this._onDisposeObserver) {
  52059. this.onDisposeObservable.remove(this._onDisposeObserver);
  52060. }
  52061. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52062. },
  52063. enumerable: true,
  52064. configurable: true
  52065. });
  52066. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52067. /**
  52068. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52069. */
  52070. get: function () {
  52071. return this._isAnimationSheetEnabled;
  52072. },
  52073. enumerable: true,
  52074. configurable: true
  52075. });
  52076. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52077. //end of Sub-emitter
  52078. /**
  52079. * Gets the current list of active particles
  52080. */
  52081. get: function () {
  52082. return this._particles;
  52083. },
  52084. enumerable: true,
  52085. configurable: true
  52086. });
  52087. /**
  52088. * Returns the string "ParticleSystem"
  52089. * @returns a string containing the class name
  52090. */
  52091. ParticleSystem.prototype.getClassName = function () {
  52092. return "ParticleSystem";
  52093. };
  52094. ParticleSystem.prototype._createIndexBuffer = function () {
  52095. var indices = [];
  52096. var index = 0;
  52097. for (var count = 0; count < this._capacity; count++) {
  52098. indices.push(index);
  52099. indices.push(index + 1);
  52100. indices.push(index + 2);
  52101. indices.push(index);
  52102. indices.push(index + 2);
  52103. indices.push(index + 3);
  52104. index += 4;
  52105. }
  52106. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52107. };
  52108. /**
  52109. * Gets the maximum number of particles active at the same time.
  52110. * @returns The max number of active particles.
  52111. */
  52112. ParticleSystem.prototype.getCapacity = function () {
  52113. return this._capacity;
  52114. };
  52115. /**
  52116. * Gets Wether there are still active particles in the system.
  52117. * @returns True if it is alive, otherwise false.
  52118. */
  52119. ParticleSystem.prototype.isAlive = function () {
  52120. return this._alive;
  52121. };
  52122. /**
  52123. * Gets Wether the system has been started.
  52124. * @returns True if it has been started, otherwise false.
  52125. */
  52126. ParticleSystem.prototype.isStarted = function () {
  52127. return this._started;
  52128. };
  52129. /**
  52130. * Starts the particle system and begins to emit.
  52131. */
  52132. ParticleSystem.prototype.start = function () {
  52133. this._started = true;
  52134. this._stopped = false;
  52135. this._actualFrame = 0;
  52136. if (this.subEmitters && this.subEmitters.length != 0) {
  52137. this.activeSubSystems = new Array();
  52138. }
  52139. };
  52140. /**
  52141. * Stops the particle system.
  52142. * @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.
  52143. */
  52144. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52145. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52146. this._stopped = true;
  52147. if (stopSubEmitters) {
  52148. this._stopSubEmitters();
  52149. }
  52150. };
  52151. // animation sheet
  52152. /**
  52153. * Remove all active particles
  52154. */
  52155. ParticleSystem.prototype.reset = function () {
  52156. this._stockParticles = [];
  52157. this._particles = [];
  52158. };
  52159. /**
  52160. * @ignore (for internal use only)
  52161. */
  52162. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52163. var offset = index * this._vertexBufferSize;
  52164. this._vertexData[offset] = particle.position.x;
  52165. this._vertexData[offset + 1] = particle.position.y;
  52166. this._vertexData[offset + 2] = particle.position.z;
  52167. this._vertexData[offset + 3] = particle.color.r;
  52168. this._vertexData[offset + 4] = particle.color.g;
  52169. this._vertexData[offset + 5] = particle.color.b;
  52170. this._vertexData[offset + 6] = particle.color.a;
  52171. this._vertexData[offset + 7] = particle.angle;
  52172. this._vertexData[offset + 8] = particle.size;
  52173. this._vertexData[offset + 9] = offsetX;
  52174. this._vertexData[offset + 10] = offsetY;
  52175. };
  52176. /**
  52177. * @ignore (for internal use only)
  52178. */
  52179. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52180. if (offsetX === 0)
  52181. offsetX = this._epsilon;
  52182. else if (offsetX === 1)
  52183. offsetX = 1 - this._epsilon;
  52184. if (offsetY === 0)
  52185. offsetY = this._epsilon;
  52186. else if (offsetY === 1)
  52187. offsetY = 1 - this._epsilon;
  52188. var offset = index * this._vertexBufferSize;
  52189. this._vertexData[offset] = particle.position.x;
  52190. this._vertexData[offset + 1] = particle.position.y;
  52191. this._vertexData[offset + 2] = particle.position.z;
  52192. this._vertexData[offset + 3] = particle.color.r;
  52193. this._vertexData[offset + 4] = particle.color.g;
  52194. this._vertexData[offset + 5] = particle.color.b;
  52195. this._vertexData[offset + 6] = particle.color.a;
  52196. this._vertexData[offset + 7] = particle.angle;
  52197. this._vertexData[offset + 8] = particle.size;
  52198. this._vertexData[offset + 9] = offsetX;
  52199. this._vertexData[offset + 10] = offsetY;
  52200. this._vertexData[offset + 11] = particle.cellIndex;
  52201. };
  52202. ParticleSystem.prototype._stopSubEmitters = function () {
  52203. if (!this.activeSubSystems) {
  52204. return;
  52205. }
  52206. this.activeSubSystems.forEach(function (subSystem) {
  52207. subSystem.stop(true);
  52208. });
  52209. this.activeSubSystems = new Array();
  52210. };
  52211. ParticleSystem.prototype._removeFromRoot = function () {
  52212. if (!this._rootParticleSystem) {
  52213. return;
  52214. }
  52215. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52216. if (index !== -1) {
  52217. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52218. }
  52219. };
  52220. // end of sub system methods
  52221. ParticleSystem.prototype._update = function (newParticles) {
  52222. // Update current
  52223. this._alive = this._particles.length > 0;
  52224. this.updateFunction(this._particles);
  52225. // Add new ones
  52226. var worldMatrix;
  52227. if (this.emitter.position) {
  52228. var emitterMesh = this.emitter;
  52229. worldMatrix = emitterMesh.getWorldMatrix();
  52230. }
  52231. else {
  52232. var emitterPosition = this.emitter;
  52233. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52234. }
  52235. var particle;
  52236. for (var index = 0; index < newParticles; index++) {
  52237. if (this._particles.length === this._capacity) {
  52238. break;
  52239. }
  52240. particle = this._createParticle();
  52241. this._particles.push(particle);
  52242. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52243. if (this.startPositionFunction) {
  52244. this.startPositionFunction(worldMatrix, particle.position, particle);
  52245. }
  52246. else {
  52247. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52248. }
  52249. if (this.startDirectionFunction) {
  52250. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52251. }
  52252. else {
  52253. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52254. }
  52255. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52256. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52257. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52258. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52259. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52260. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52261. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52262. }
  52263. };
  52264. ParticleSystem.prototype._getEffect = function () {
  52265. if (this._customEffect) {
  52266. return this._customEffect;
  52267. }
  52268. ;
  52269. var defines = [];
  52270. if (this._scene.clipPlane) {
  52271. defines.push("#define CLIPPLANE");
  52272. }
  52273. if (this._isAnimationSheetEnabled) {
  52274. defines.push("#define ANIMATESHEET");
  52275. }
  52276. // Effect
  52277. var join = defines.join("\n");
  52278. if (this._cachedDefines !== join) {
  52279. this._cachedDefines = join;
  52280. var attributesNamesOrOptions;
  52281. var effectCreationOption;
  52282. if (this._isAnimationSheetEnabled) {
  52283. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52284. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52285. }
  52286. else {
  52287. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52288. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52289. }
  52290. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52291. }
  52292. return this._effect;
  52293. };
  52294. /**
  52295. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52296. */
  52297. ParticleSystem.prototype.animate = function () {
  52298. if (!this._started)
  52299. return;
  52300. var effect = this._getEffect();
  52301. // Check
  52302. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52303. return;
  52304. if (this._currentRenderId === this._scene.getRenderId()) {
  52305. return;
  52306. }
  52307. this._currentRenderId = this._scene.getRenderId();
  52308. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52309. // determine the number of particles we need to create
  52310. var newParticles;
  52311. if (this.manualEmitCount > -1) {
  52312. newParticles = this.manualEmitCount;
  52313. this._newPartsExcess = 0;
  52314. this.manualEmitCount = 0;
  52315. }
  52316. else {
  52317. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52318. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52319. }
  52320. if (this._newPartsExcess > 1.0) {
  52321. newParticles += this._newPartsExcess >> 0;
  52322. this._newPartsExcess -= this._newPartsExcess >> 0;
  52323. }
  52324. this._alive = false;
  52325. if (!this._stopped) {
  52326. this._actualFrame += this._scaledUpdateSpeed;
  52327. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52328. this.stop();
  52329. }
  52330. else {
  52331. newParticles = 0;
  52332. }
  52333. this._update(newParticles);
  52334. // Stopped?
  52335. if (this._stopped) {
  52336. if (!this._alive) {
  52337. this._started = false;
  52338. if (this.onAnimationEnd) {
  52339. this.onAnimationEnd();
  52340. }
  52341. if (this.disposeOnStop) {
  52342. this._scene._toBeDisposed.push(this);
  52343. }
  52344. }
  52345. }
  52346. // Animation sheet
  52347. if (this._isAnimationSheetEnabled) {
  52348. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52349. }
  52350. else {
  52351. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52352. }
  52353. // Update VBO
  52354. var offset = 0;
  52355. for (var index = 0; index < this._particles.length; index++) {
  52356. var particle = this._particles[index];
  52357. this._appendParticleVertexes(offset, particle);
  52358. offset += 4;
  52359. }
  52360. if (this._vertexBuffer) {
  52361. this._vertexBuffer.update(this._vertexData);
  52362. }
  52363. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52364. this.stop();
  52365. }
  52366. };
  52367. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52368. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52369. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52370. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52371. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52372. };
  52373. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52374. this._appendParticleVertex(offset++, particle, 0, 0);
  52375. this._appendParticleVertex(offset++, particle, 1, 0);
  52376. this._appendParticleVertex(offset++, particle, 1, 1);
  52377. this._appendParticleVertex(offset++, particle, 0, 1);
  52378. };
  52379. /**
  52380. * Rebuilds the particle system.
  52381. */
  52382. ParticleSystem.prototype.rebuild = function () {
  52383. this._createIndexBuffer();
  52384. if (this._vertexBuffer) {
  52385. this._vertexBuffer._rebuild();
  52386. }
  52387. };
  52388. /**
  52389. * Is this system ready to be used/rendered
  52390. * @return true if the system is ready
  52391. */
  52392. ParticleSystem.prototype.isReady = function () {
  52393. var effect = this._getEffect();
  52394. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52395. return false;
  52396. }
  52397. return true;
  52398. };
  52399. /**
  52400. * Renders the particle system in its current state.
  52401. * @returns the current number of particles
  52402. */
  52403. ParticleSystem.prototype.render = function () {
  52404. var effect = this._getEffect();
  52405. // Check
  52406. if (!this.isReady() || !this._particles.length) {
  52407. return 0;
  52408. }
  52409. var engine = this._scene.getEngine();
  52410. // Render
  52411. engine.enableEffect(effect);
  52412. engine.setState(false);
  52413. var viewMatrix = this._scene.getViewMatrix();
  52414. effect.setTexture("diffuseSampler", this.particleTexture);
  52415. effect.setMatrix("view", viewMatrix);
  52416. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52417. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52418. var baseSize = this.particleTexture.getBaseSize();
  52419. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52420. }
  52421. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52422. if (this._scene.clipPlane) {
  52423. var clipPlane = this._scene.clipPlane;
  52424. var invView = viewMatrix.clone();
  52425. invView.invert();
  52426. effect.setMatrix("invView", invView);
  52427. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52428. }
  52429. // VBOs
  52430. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52431. // Draw order
  52432. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52433. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52434. }
  52435. else {
  52436. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52437. }
  52438. if (this.forceDepthWrite) {
  52439. engine.setDepthWrite(true);
  52440. }
  52441. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52443. return this._particles.length;
  52444. };
  52445. /**
  52446. * Disposes the particle system and free the associated resources
  52447. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52448. */
  52449. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52450. if (disposeTexture === void 0) { disposeTexture = true; }
  52451. if (this._vertexBuffer) {
  52452. this._vertexBuffer.dispose();
  52453. this._vertexBuffer = null;
  52454. }
  52455. if (this._indexBuffer) {
  52456. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52457. this._indexBuffer = null;
  52458. }
  52459. if (disposeTexture && this.particleTexture) {
  52460. this.particleTexture.dispose();
  52461. this.particleTexture = null;
  52462. }
  52463. this._removeFromRoot();
  52464. // Remove from scene
  52465. var index = this._scene.particleSystems.indexOf(this);
  52466. if (index > -1) {
  52467. this._scene.particleSystems.splice(index, 1);
  52468. }
  52469. // Callback
  52470. this.onDisposeObservable.notifyObservers(this);
  52471. this.onDisposeObservable.clear();
  52472. };
  52473. /**
  52474. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52475. * @param radius The radius of the sphere to emit from
  52476. * @returns the emitter
  52477. */
  52478. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52479. if (radius === void 0) { radius = 1; }
  52480. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52481. this.particleEmitterType = particleEmitter;
  52482. return particleEmitter;
  52483. };
  52484. /**
  52485. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52486. * @param radius The radius of the sphere to emit from
  52487. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52488. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52489. * @returns the emitter
  52490. */
  52491. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52492. if (radius === void 0) { radius = 1; }
  52493. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52494. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52495. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52496. this.particleEmitterType = particleEmitter;
  52497. return particleEmitter;
  52498. };
  52499. /**
  52500. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52501. * @param radius The radius of the cone to emit from
  52502. * @param angle The base angle of the cone
  52503. * @returns the emitter
  52504. */
  52505. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52506. if (radius === void 0) { radius = 1; }
  52507. if (angle === void 0) { angle = Math.PI / 4; }
  52508. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52509. this.particleEmitterType = particleEmitter;
  52510. return particleEmitter;
  52511. };
  52512. // 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.
  52513. /**
  52514. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52515. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52516. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52517. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52518. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52519. * @returns the emitter
  52520. */
  52521. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52522. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52523. this.particleEmitterType = particleEmitter;
  52524. this.direction1 = direction1;
  52525. this.direction2 = direction2;
  52526. this.minEmitBox = minEmitBox;
  52527. this.maxEmitBox = maxEmitBox;
  52528. return particleEmitter;
  52529. };
  52530. // Clone
  52531. /**
  52532. * Clones the particle system.
  52533. * @param name The name of the cloned object
  52534. * @param newEmitter The new emitter to use
  52535. * @returns the cloned particle system
  52536. */
  52537. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52538. var custom = null;
  52539. var program = null;
  52540. if (this.customShader != null) {
  52541. program = this.customShader;
  52542. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52543. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52544. }
  52545. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52546. result.customShader = program;
  52547. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52548. if (newEmitter === undefined) {
  52549. newEmitter = this.emitter;
  52550. }
  52551. result.emitter = newEmitter;
  52552. if (this.particleTexture) {
  52553. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52554. }
  52555. if (!this.preventAutoStart) {
  52556. result.start();
  52557. }
  52558. return result;
  52559. };
  52560. /**
  52561. * Serializes the particle system to a JSON object.
  52562. * @returns the JSON object
  52563. */
  52564. ParticleSystem.prototype.serialize = function () {
  52565. var serializationObject = {};
  52566. serializationObject.name = this.name;
  52567. serializationObject.id = this.id;
  52568. // Emitter
  52569. if (this.emitter.position) {
  52570. var emitterMesh = this.emitter;
  52571. serializationObject.emitterId = emitterMesh.id;
  52572. }
  52573. else {
  52574. var emitterPosition = this.emitter;
  52575. serializationObject.emitter = emitterPosition.asArray();
  52576. }
  52577. serializationObject.capacity = this.getCapacity();
  52578. if (this.particleTexture) {
  52579. serializationObject.textureName = this.particleTexture.name;
  52580. }
  52581. // Animations
  52582. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52583. // Particle system
  52584. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52585. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52586. serializationObject.minSize = this.minSize;
  52587. serializationObject.maxSize = this.maxSize;
  52588. serializationObject.minEmitPower = this.minEmitPower;
  52589. serializationObject.maxEmitPower = this.maxEmitPower;
  52590. serializationObject.minLifeTime = this.minLifeTime;
  52591. serializationObject.maxLifeTime = this.maxLifeTime;
  52592. serializationObject.emitRate = this.emitRate;
  52593. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52594. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52595. serializationObject.gravity = this.gravity.asArray();
  52596. serializationObject.direction1 = this.direction1.asArray();
  52597. serializationObject.direction2 = this.direction2.asArray();
  52598. serializationObject.color1 = this.color1.asArray();
  52599. serializationObject.color2 = this.color2.asArray();
  52600. serializationObject.colorDead = this.colorDead.asArray();
  52601. serializationObject.updateSpeed = this.updateSpeed;
  52602. serializationObject.targetStopDuration = this.targetStopDuration;
  52603. serializationObject.textureMask = this.textureMask.asArray();
  52604. serializationObject.blendMode = this.blendMode;
  52605. serializationObject.customShader = this.customShader;
  52606. serializationObject.preventAutoStart = this.preventAutoStart;
  52607. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52608. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52609. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52610. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52611. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52612. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52613. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52614. // Emitter
  52615. if (this.particleEmitterType) {
  52616. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52617. }
  52618. return serializationObject;
  52619. };
  52620. /**
  52621. * Parses a JSON object to create a particle system.
  52622. * @param parsedParticleSystem The JSON object to parse
  52623. * @param scene The scene to create the particle system in
  52624. * @param rootUrl The root url to use to load external dependencies like texture
  52625. * @returns the Parsed particle system
  52626. */
  52627. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52628. var name = parsedParticleSystem.name;
  52629. var custom = null;
  52630. var program = null;
  52631. if (parsedParticleSystem.customShader) {
  52632. program = parsedParticleSystem.customShader;
  52633. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52634. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52635. }
  52636. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52637. particleSystem.customShader = program;
  52638. if (parsedParticleSystem.id) {
  52639. particleSystem.id = parsedParticleSystem.id;
  52640. }
  52641. // Auto start
  52642. if (parsedParticleSystem.preventAutoStart) {
  52643. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52644. }
  52645. // Texture
  52646. if (parsedParticleSystem.textureName) {
  52647. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52648. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52649. }
  52650. // Emitter
  52651. if (parsedParticleSystem.emitterId) {
  52652. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52653. }
  52654. else {
  52655. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52656. }
  52657. // Animations
  52658. if (parsedParticleSystem.animations) {
  52659. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52660. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52661. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52662. }
  52663. }
  52664. if (parsedParticleSystem.autoAnimate) {
  52665. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52666. }
  52667. // Particle system
  52668. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52669. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52670. particleSystem.minSize = parsedParticleSystem.minSize;
  52671. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52672. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52673. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52674. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52675. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52676. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52677. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52678. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52679. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52680. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52681. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52682. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52683. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52684. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52685. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52686. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52687. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52688. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52689. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52690. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52691. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52692. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52693. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52694. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52695. if (!particleSystem.preventAutoStart) {
  52696. particleSystem.start();
  52697. }
  52698. return particleSystem;
  52699. };
  52700. /**
  52701. * Source color is added to the destination color without alpha affecting the result.
  52702. */
  52703. ParticleSystem.BLENDMODE_ONEONE = 0;
  52704. /**
  52705. * Blend current color and particle color using particle’s alpha.
  52706. */
  52707. ParticleSystem.BLENDMODE_STANDARD = 1;
  52708. return ParticleSystem;
  52709. }());
  52710. BABYLON.ParticleSystem = ParticleSystem;
  52711. })(BABYLON || (BABYLON = {}));
  52712. //# sourceMappingURL=babylon.particleSystem.js.map
  52713. "use strict";
  52714. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52715. "use strict";
  52716. var BABYLON;
  52717. (function (BABYLON) {
  52718. /**
  52719. * Particle emitter emitting particles from the inside of a box.
  52720. * It emits the particles randomly between 2 given directions.
  52721. */
  52722. var BoxParticleEmitter = /** @class */ (function () {
  52723. /**
  52724. * Creates a new instance BoxParticleEmitter
  52725. */
  52726. function BoxParticleEmitter() {
  52727. /**
  52728. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52729. */
  52730. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52731. /**
  52732. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52733. */
  52734. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52735. /**
  52736. * 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.
  52737. */
  52738. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52739. /**
  52740. * 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.
  52741. */
  52742. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52743. }
  52744. /**
  52745. * Called by the particle System when the direction is computed for the created particle.
  52746. * @param emitPower is the power of the particle (speed)
  52747. * @param worldMatrix is the world matrix of the particle system
  52748. * @param directionToUpdate is the direction vector to update with the result
  52749. * @param particle is the particle we are computed the direction for
  52750. */
  52751. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52752. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52753. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52754. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52755. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52756. };
  52757. /**
  52758. * Called by the particle System when the position is computed for the created particle.
  52759. * @param worldMatrix is the world matrix of the particle system
  52760. * @param positionToUpdate is the position vector to update with the result
  52761. * @param particle is the particle we are computed the position for
  52762. */
  52763. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52764. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52765. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52766. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52767. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52768. };
  52769. /**
  52770. * Clones the current emitter and returns a copy of it
  52771. * @returns the new emitter
  52772. */
  52773. BoxParticleEmitter.prototype.clone = function () {
  52774. var newOne = new BoxParticleEmitter();
  52775. BABYLON.Tools.DeepCopy(this, newOne);
  52776. return newOne;
  52777. };
  52778. /**
  52779. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52780. * @param effect defines the update shader
  52781. */
  52782. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52783. effect.setVector3("direction1", this.direction1);
  52784. effect.setVector3("direction2", this.direction2);
  52785. effect.setVector3("minEmitBox", this.minEmitBox);
  52786. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52787. };
  52788. /**
  52789. * Returns a string to use to update the GPU particles update shader
  52790. * @returns a string containng the defines string
  52791. */
  52792. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52793. return "#define BOXEMITTER";
  52794. };
  52795. /**
  52796. * Returns the string "BoxEmitter"
  52797. * @returns a string containing the class name
  52798. */
  52799. BoxParticleEmitter.prototype.getClassName = function () {
  52800. return "BoxEmitter";
  52801. };
  52802. /**
  52803. * Serializes the particle system to a JSON object.
  52804. * @returns the JSON object
  52805. */
  52806. BoxParticleEmitter.prototype.serialize = function () {
  52807. var serializationObject = {};
  52808. serializationObject.type = this.getClassName();
  52809. serializationObject.direction1 = this.direction1.asArray();
  52810. ;
  52811. serializationObject.direction2 = this.direction2.asArray();
  52812. ;
  52813. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52814. ;
  52815. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52816. ;
  52817. return serializationObject;
  52818. };
  52819. /**
  52820. * Parse properties from a JSON object
  52821. * @param serializationObject defines the JSON object
  52822. */
  52823. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52824. this.direction1.copyFrom(serializationObject.direction1);
  52825. this.direction2.copyFrom(serializationObject.direction2);
  52826. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52827. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52828. };
  52829. return BoxParticleEmitter;
  52830. }());
  52831. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52832. })(BABYLON || (BABYLON = {}));
  52833. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52834. "use strict";
  52835. var BABYLON;
  52836. (function (BABYLON) {
  52837. /**
  52838. * Particle emitter emitting particles from the inside of a cone.
  52839. * It emits the particles alongside the cone volume from the base to the particle.
  52840. * The emission direction might be randomized.
  52841. */
  52842. var ConeParticleEmitter = /** @class */ (function () {
  52843. /**
  52844. * Creates a new instance ConeParticleEmitter
  52845. * @param radius the radius of the emission cone (1 by default)
  52846. * @param angles the cone base angle (PI by default)
  52847. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52848. */
  52849. function ConeParticleEmitter(radius,
  52850. /**
  52851. * The radius of the emission cone.
  52852. */
  52853. angle,
  52854. /**
  52855. * The cone base angle.
  52856. */
  52857. directionRandomizer) {
  52858. if (radius === void 0) { radius = 1; }
  52859. if (angle === void 0) { angle = Math.PI; }
  52860. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52861. this.angle = angle;
  52862. this.directionRandomizer = directionRandomizer;
  52863. this.radius = radius;
  52864. }
  52865. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52866. /**
  52867. * Gets the radius of the emission cone.
  52868. */
  52869. get: function () {
  52870. return this._radius;
  52871. },
  52872. /**
  52873. * Sets the radius of the emission cone.
  52874. */
  52875. set: function (value) {
  52876. this._radius = value;
  52877. if (this.angle !== 0) {
  52878. this._height = value / Math.tan(this.angle / 2);
  52879. }
  52880. else {
  52881. this._height = 1;
  52882. }
  52883. },
  52884. enumerable: true,
  52885. configurable: true
  52886. });
  52887. /**
  52888. * Called by the particle System when the direction is computed for the created particle.
  52889. * @param emitPower is the power of the particle (speed)
  52890. * @param worldMatrix is the world matrix of the particle system
  52891. * @param directionToUpdate is the direction vector to update with the result
  52892. * @param particle is the particle we are computed the direction for
  52893. */
  52894. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52895. if (this.angle === 0) {
  52896. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52897. }
  52898. else {
  52899. // measure the direction Vector from the emitter to the particle.
  52900. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52901. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52902. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52903. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52904. direction.x += randX;
  52905. direction.y += randY;
  52906. direction.z += randZ;
  52907. direction.normalize();
  52908. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52909. }
  52910. };
  52911. /**
  52912. * Called by the particle System when the position is computed for the created particle.
  52913. * @param worldMatrix is the world matrix of the particle system
  52914. * @param positionToUpdate is the position vector to update with the result
  52915. * @param particle is the particle we are computed the position for
  52916. */
  52917. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52918. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52919. var h = BABYLON.Scalar.RandomRange(0, 1);
  52920. // Better distribution in a cone at normal angles.
  52921. h = 1 - h * h;
  52922. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52923. radius = radius * h;
  52924. var randX = radius * Math.sin(s);
  52925. var randZ = radius * Math.cos(s);
  52926. var randY = h * this._height;
  52927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52928. };
  52929. /**
  52930. * Clones the current emitter and returns a copy of it
  52931. * @returns the new emitter
  52932. */
  52933. ConeParticleEmitter.prototype.clone = function () {
  52934. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52935. BABYLON.Tools.DeepCopy(this, newOne);
  52936. return newOne;
  52937. };
  52938. /**
  52939. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52940. * @param effect defines the update shader
  52941. */
  52942. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52943. effect.setFloat("radius", this.radius);
  52944. effect.setFloat("angle", this.angle);
  52945. effect.setFloat("height", this._height);
  52946. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52947. };
  52948. /**
  52949. * Returns a string to use to update the GPU particles update shader
  52950. * @returns a string containng the defines string
  52951. */
  52952. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52953. return "#define CONEEMITTER";
  52954. };
  52955. /**
  52956. * Returns the string "BoxEmitter"
  52957. * @returns a string containing the class name
  52958. */
  52959. ConeParticleEmitter.prototype.getClassName = function () {
  52960. return "ConeEmitter";
  52961. };
  52962. /**
  52963. * Serializes the particle system to a JSON object.
  52964. * @returns the JSON object
  52965. */
  52966. ConeParticleEmitter.prototype.serialize = function () {
  52967. var serializationObject = {};
  52968. serializationObject.type = this.getClassName();
  52969. serializationObject.radius = this.radius;
  52970. serializationObject.angle = this.angle;
  52971. serializationObject.directionRandomizer = this.directionRandomizer;
  52972. return serializationObject;
  52973. };
  52974. /**
  52975. * Parse properties from a JSON object
  52976. * @param serializationObject defines the JSON object
  52977. */
  52978. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52979. this.radius = serializationObject.radius;
  52980. this.angle = serializationObject.angle;
  52981. this.directionRandomizer = serializationObject.directionRandomizer;
  52982. };
  52983. return ConeParticleEmitter;
  52984. }());
  52985. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52986. })(BABYLON || (BABYLON = {}));
  52987. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52988. "use strict";
  52989. var BABYLON;
  52990. (function (BABYLON) {
  52991. /**
  52992. * Particle emitter emitting particles from the inside of a sphere.
  52993. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52994. */
  52995. var SphereParticleEmitter = /** @class */ (function () {
  52996. /**
  52997. * Creates a new instance SphereParticleEmitter
  52998. * @param radius the radius of the emission sphere (1 by default)
  52999. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  53000. */
  53001. function SphereParticleEmitter(
  53002. /**
  53003. * The radius of the emission sphere.
  53004. */
  53005. radius,
  53006. /**
  53007. * How much to randomize the particle direction [0-1].
  53008. */
  53009. directionRandomizer) {
  53010. if (radius === void 0) { radius = 1; }
  53011. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  53012. this.radius = radius;
  53013. this.directionRandomizer = directionRandomizer;
  53014. }
  53015. /**
  53016. * Called by the particle System when the direction is computed for the created particle.
  53017. * @param emitPower is the power of the particle (speed)
  53018. * @param worldMatrix is the world matrix of the particle system
  53019. * @param directionToUpdate is the direction vector to update with the result
  53020. * @param particle is the particle we are computed the direction for
  53021. */
  53022. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53023. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  53024. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53025. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53026. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53027. direction.x += randX;
  53028. direction.y += randY;
  53029. direction.z += randZ;
  53030. direction.normalize();
  53031. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53032. };
  53033. /**
  53034. * Called by the particle System when the position is computed for the created particle.
  53035. * @param worldMatrix is the world matrix of the particle system
  53036. * @param positionToUpdate is the position vector to update with the result
  53037. * @param particle is the particle we are computed the position for
  53038. */
  53039. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53040. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  53041. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  53042. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  53043. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  53044. var randY = randRadius * Math.cos(theta);
  53045. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  53046. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53047. };
  53048. /**
  53049. * Clones the current emitter and returns a copy of it
  53050. * @returns the new emitter
  53051. */
  53052. SphereParticleEmitter.prototype.clone = function () {
  53053. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  53054. BABYLON.Tools.DeepCopy(this, newOne);
  53055. return newOne;
  53056. };
  53057. /**
  53058. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53059. * @param effect defines the update shader
  53060. */
  53061. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53062. effect.setFloat("radius", this.radius);
  53063. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53064. };
  53065. /**
  53066. * Returns a string to use to update the GPU particles update shader
  53067. * @returns a string containng the defines string
  53068. */
  53069. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53070. return "#define SPHEREEMITTER";
  53071. };
  53072. /**
  53073. * Returns the string "SphereParticleEmitter"
  53074. * @returns a string containing the class name
  53075. */
  53076. SphereParticleEmitter.prototype.getClassName = function () {
  53077. return "SphereParticleEmitter";
  53078. };
  53079. /**
  53080. * Serializes the particle system to a JSON object.
  53081. * @returns the JSON object
  53082. */
  53083. SphereParticleEmitter.prototype.serialize = function () {
  53084. var serializationObject = {};
  53085. serializationObject.type = this.getClassName();
  53086. serializationObject.radius = this.radius;
  53087. serializationObject.directionRandomizer = this.directionRandomizer;
  53088. return serializationObject;
  53089. };
  53090. /**
  53091. * Parse properties from a JSON object
  53092. * @param serializationObject defines the JSON object
  53093. */
  53094. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53095. this.radius = serializationObject.radius;
  53096. this.directionRandomizer = serializationObject.directionRandomizer;
  53097. };
  53098. return SphereParticleEmitter;
  53099. }());
  53100. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53101. /**
  53102. * Particle emitter emitting particles from the inside of a sphere.
  53103. * It emits the particles randomly between two vectors.
  53104. */
  53105. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53106. __extends(SphereDirectedParticleEmitter, _super);
  53107. /**
  53108. * Creates a new instance SphereDirectedParticleEmitter
  53109. * @param radius the radius of the emission sphere (1 by default)
  53110. * @param direction1 the min limit of the emission direction (up vector by default)
  53111. * @param direction2 the max limit of the emission direction (up vector by default)
  53112. */
  53113. function SphereDirectedParticleEmitter(radius,
  53114. /**
  53115. * The min limit of the emission direction.
  53116. */
  53117. direction1,
  53118. /**
  53119. * The max limit of the emission direction.
  53120. */
  53121. direction2) {
  53122. if (radius === void 0) { radius = 1; }
  53123. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53124. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53125. var _this = _super.call(this, radius) || this;
  53126. _this.direction1 = direction1;
  53127. _this.direction2 = direction2;
  53128. return _this;
  53129. }
  53130. /**
  53131. * Called by the particle System when the direction is computed for the created particle.
  53132. * @param emitPower is the power of the particle (speed)
  53133. * @param worldMatrix is the world matrix of the particle system
  53134. * @param directionToUpdate is the direction vector to update with the result
  53135. * @param particle is the particle we are computed the direction for
  53136. */
  53137. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53138. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53139. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53140. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53141. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53142. };
  53143. /**
  53144. * Clones the current emitter and returns a copy of it
  53145. * @returns the new emitter
  53146. */
  53147. SphereDirectedParticleEmitter.prototype.clone = function () {
  53148. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53149. BABYLON.Tools.DeepCopy(this, newOne);
  53150. return newOne;
  53151. };
  53152. /**
  53153. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53154. * @param effect defines the update shader
  53155. */
  53156. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53157. effect.setFloat("radius", this.radius);
  53158. effect.setVector3("direction1", this.direction1);
  53159. effect.setVector3("direction2", this.direction2);
  53160. };
  53161. /**
  53162. * Returns a string to use to update the GPU particles update shader
  53163. * @returns a string containng the defines string
  53164. */
  53165. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53166. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53167. };
  53168. /**
  53169. * Returns the string "SphereDirectedParticleEmitter"
  53170. * @returns a string containing the class name
  53171. */
  53172. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53173. return "SphereDirectedParticleEmitter";
  53174. };
  53175. /**
  53176. * Serializes the particle system to a JSON object.
  53177. * @returns the JSON object
  53178. */
  53179. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53180. var serializationObject = _super.prototype.serialize.call(this);
  53181. ;
  53182. serializationObject.direction1 = this.direction1.asArray();
  53183. ;
  53184. serializationObject.direction2 = this.direction2.asArray();
  53185. ;
  53186. return serializationObject;
  53187. };
  53188. /**
  53189. * Parse properties from a JSON object
  53190. * @param serializationObject defines the JSON object
  53191. */
  53192. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53193. _super.prototype.parse.call(this, serializationObject);
  53194. this.direction1.copyFrom(serializationObject.direction1);
  53195. this.direction2.copyFrom(serializationObject.direction2);
  53196. };
  53197. return SphereDirectedParticleEmitter;
  53198. }(SphereParticleEmitter));
  53199. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53200. })(BABYLON || (BABYLON = {}));
  53201. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53202. "use strict";
  53203. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53204. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53205. s = arguments[i];
  53206. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53207. t[p] = s[p];
  53208. }
  53209. return t;
  53210. };
  53211. var BABYLON;
  53212. (function (BABYLON) {
  53213. /**
  53214. * This represents a GPU particle system in Babylon
  53215. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53216. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53217. */
  53218. var GPUParticleSystem = /** @class */ (function () {
  53219. /**
  53220. * Instantiates a GPU particle system.
  53221. * 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.
  53222. * @param name The name of the particle system
  53223. * @param capacity The max number of particles alive at the same time
  53224. * @param scene The scene the particle system belongs to
  53225. */
  53226. function GPUParticleSystem(name, options, scene) {
  53227. /**
  53228. * The emitter represents the Mesh or position we are attaching the particle system to.
  53229. */
  53230. this.emitter = null;
  53231. /**
  53232. * The rendering group used by the Particle system to chose when to render.
  53233. */
  53234. this.renderingGroupId = 0;
  53235. /**
  53236. * The layer mask we are rendering the particles through.
  53237. */
  53238. this.layerMask = 0x0FFFFFFF;
  53239. this._targetIndex = 0;
  53240. this._currentRenderId = -1;
  53241. this._started = false;
  53242. this._stopped = false;
  53243. this._timeDelta = 0;
  53244. this._attributesStrideSize = 14;
  53245. this._actualFrame = 0;
  53246. /**
  53247. * List of animations used by the particle system.
  53248. */
  53249. this.animations = [];
  53250. /**
  53251. * An event triggered when the system is disposed.
  53252. */
  53253. this.onDisposeObservable = new BABYLON.Observable();
  53254. /**
  53255. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53256. */
  53257. this.updateSpeed = 0.01;
  53258. /**
  53259. * The amount of time the particle system is running (depends of the overall update speed).
  53260. */
  53261. this.targetStopDuration = 0;
  53262. /**
  53263. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53264. */
  53265. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53266. /**
  53267. * Minimum life time of emitting particles.
  53268. */
  53269. this.minLifeTime = 1;
  53270. /**
  53271. * Maximum life time of emitting particles.
  53272. */
  53273. this.maxLifeTime = 1;
  53274. /**
  53275. * Minimum Size of emitting particles.
  53276. */
  53277. this.minSize = 1;
  53278. /**
  53279. * Maximum Size of emitting particles.
  53280. */
  53281. this.maxSize = 1;
  53282. /**
  53283. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53284. */
  53285. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53286. /**
  53287. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53288. */
  53289. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53290. /**
  53291. * Color the particle will have at the end of its lifetime.
  53292. */
  53293. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53294. /**
  53295. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53296. */
  53297. this.emitRate = 100;
  53298. /**
  53299. * You can use gravity if you want to give an orientation to your particles.
  53300. */
  53301. this.gravity = BABYLON.Vector3.Zero();
  53302. /**
  53303. * Minimum power of emitting particles.
  53304. */
  53305. this.minEmitPower = 1;
  53306. /**
  53307. * Maximum power of emitting particles.
  53308. */
  53309. this.maxEmitPower = 1;
  53310. /**
  53311. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53312. * to override the particles.
  53313. */
  53314. this.forceDepthWrite = false;
  53315. this.id = name;
  53316. this.name = name;
  53317. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53318. this._engine = this._scene.getEngine();
  53319. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53320. this._capacity = fullOptions.capacity;
  53321. this._activeCount = fullOptions.capacity;
  53322. this._currentActiveCount = 0;
  53323. this._scene.particleSystems.push(this);
  53324. this._updateEffectOptions = {
  53325. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53326. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53327. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53328. uniformBuffersNames: [],
  53329. samplers: ["randomSampler"],
  53330. defines: "",
  53331. fallbacks: null,
  53332. onCompiled: null,
  53333. onError: null,
  53334. indexParameters: null,
  53335. maxSimultaneousLights: 0,
  53336. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53337. };
  53338. // Random data
  53339. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53340. var d = [];
  53341. for (var i = 0; i < maxTextureSize; ++i) {
  53342. d.push(Math.random());
  53343. d.push(Math.random());
  53344. d.push(Math.random());
  53345. d.push(Math.random());
  53346. }
  53347. 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);
  53348. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53349. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53350. this._randomTextureSize = maxTextureSize;
  53351. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53352. }
  53353. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53354. /**
  53355. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53356. */
  53357. get: function () {
  53358. if (!BABYLON.Engine.LastCreatedEngine) {
  53359. return false;
  53360. }
  53361. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53362. },
  53363. enumerable: true,
  53364. configurable: true
  53365. });
  53366. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53367. /**
  53368. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53369. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53370. */
  53371. get: function () {
  53372. if (this.particleEmitterType.direction1) {
  53373. return this.particleEmitterType.direction1;
  53374. }
  53375. return BABYLON.Vector3.Zero();
  53376. },
  53377. set: function (value) {
  53378. if (this.particleEmitterType.direction1) {
  53379. this.particleEmitterType.direction1 = value;
  53380. }
  53381. },
  53382. enumerable: true,
  53383. configurable: true
  53384. });
  53385. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53386. /**
  53387. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53388. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53389. */
  53390. get: function () {
  53391. if (this.particleEmitterType.direction2) {
  53392. return this.particleEmitterType.direction2;
  53393. }
  53394. return BABYLON.Vector3.Zero();
  53395. },
  53396. set: function (value) {
  53397. if (this.particleEmitterType.direction2) {
  53398. this.particleEmitterType.direction2 = value;
  53399. }
  53400. },
  53401. enumerable: true,
  53402. configurable: true
  53403. });
  53404. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53405. /**
  53406. * 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.
  53407. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53408. */
  53409. get: function () {
  53410. if (this.particleEmitterType.minEmitBox) {
  53411. return this.particleEmitterType.minEmitBox;
  53412. }
  53413. return BABYLON.Vector3.Zero();
  53414. },
  53415. set: function (value) {
  53416. if (this.particleEmitterType.minEmitBox) {
  53417. this.particleEmitterType.minEmitBox = value;
  53418. }
  53419. },
  53420. enumerable: true,
  53421. configurable: true
  53422. });
  53423. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53424. /**
  53425. * 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.
  53426. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53427. */
  53428. get: function () {
  53429. if (this.particleEmitterType.maxEmitBox) {
  53430. return this.particleEmitterType.maxEmitBox;
  53431. }
  53432. return BABYLON.Vector3.Zero();
  53433. },
  53434. set: function (value) {
  53435. if (this.particleEmitterType.maxEmitBox) {
  53436. this.particleEmitterType.maxEmitBox = value;
  53437. }
  53438. },
  53439. enumerable: true,
  53440. configurable: true
  53441. });
  53442. /**
  53443. * Gets the maximum number of particles active at the same time.
  53444. * @returns The max number of active particles.
  53445. */
  53446. GPUParticleSystem.prototype.getCapacity = function () {
  53447. return this._capacity;
  53448. };
  53449. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53450. /**
  53451. * Gets or set the number of active particles
  53452. */
  53453. get: function () {
  53454. return this._activeCount;
  53455. },
  53456. set: function (value) {
  53457. this._activeCount = Math.min(value, this._capacity);
  53458. },
  53459. enumerable: true,
  53460. configurable: true
  53461. });
  53462. /**
  53463. * Is this system ready to be used/rendered
  53464. * @return true if the system is ready
  53465. */
  53466. GPUParticleSystem.prototype.isReady = function () {
  53467. if (!this._updateEffect) {
  53468. this._recreateUpdateEffect();
  53469. this._recreateRenderEffect();
  53470. return false;
  53471. }
  53472. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53473. return false;
  53474. }
  53475. return true;
  53476. };
  53477. /**
  53478. * Gets Wether the system has been started.
  53479. * @returns True if it has been started, otherwise false.
  53480. */
  53481. GPUParticleSystem.prototype.isStarted = function () {
  53482. return this._started;
  53483. };
  53484. /**
  53485. * Starts the particle system and begins to emit.
  53486. */
  53487. GPUParticleSystem.prototype.start = function () {
  53488. this._started = true;
  53489. this._stopped = false;
  53490. };
  53491. /**
  53492. * Stops the particle system.
  53493. */
  53494. GPUParticleSystem.prototype.stop = function () {
  53495. this._stopped = true;
  53496. };
  53497. /**
  53498. * Remove all active particles
  53499. */
  53500. GPUParticleSystem.prototype.reset = function () {
  53501. this._releaseBuffers();
  53502. this._releaseVAOs();
  53503. this._currentActiveCount = 0;
  53504. this._targetIndex = 0;
  53505. };
  53506. /**
  53507. * Returns the string "GPUParticleSystem"
  53508. * @returns a string containing the class name
  53509. */
  53510. GPUParticleSystem.prototype.getClassName = function () {
  53511. return "GPUParticleSystem";
  53512. };
  53513. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53514. var updateVertexBuffers = {};
  53515. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53516. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53517. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53518. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53519. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53520. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53521. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53522. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53523. this._engine.bindArrayBuffer(null);
  53524. return vao;
  53525. };
  53526. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53527. var renderVertexBuffers = {};
  53528. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53529. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53530. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53531. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53532. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53533. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53534. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53535. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53536. this._engine.bindArrayBuffer(null);
  53537. return vao;
  53538. };
  53539. GPUParticleSystem.prototype._initialize = function (force) {
  53540. if (force === void 0) { force = false; }
  53541. if (this._buffer0 && !force) {
  53542. return;
  53543. }
  53544. var engine = this._scene.getEngine();
  53545. var data = new Array();
  53546. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53547. // position
  53548. data.push(0.0);
  53549. data.push(0.0);
  53550. data.push(0.0);
  53551. // Age and life
  53552. data.push(0.0); // create the particle as a dead one to create a new one at start
  53553. data.push(0.0);
  53554. // Seed
  53555. data.push(Math.random());
  53556. // Size
  53557. data.push(0.0);
  53558. // color
  53559. data.push(0.0);
  53560. data.push(0.0);
  53561. data.push(0.0);
  53562. data.push(0.0);
  53563. // direction
  53564. data.push(0.0);
  53565. data.push(0.0);
  53566. data.push(0.0);
  53567. }
  53568. // Sprite data
  53569. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53570. -0.5, 0.5, 0, 1,
  53571. -0.5, -0.5, 0, 0,
  53572. 0.5, -0.5, 1, 0]);
  53573. // Buffers
  53574. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53575. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53576. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53577. // Update VAO
  53578. this._updateVAO = [];
  53579. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53580. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53581. // Render VAO
  53582. this._renderVAO = [];
  53583. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53584. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53585. // Links
  53586. this._sourceBuffer = this._buffer0;
  53587. this._targetBuffer = this._buffer1;
  53588. };
  53589. /** @ignore */
  53590. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53591. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53592. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53593. return;
  53594. }
  53595. this._updateEffectOptions.defines = defines;
  53596. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53597. };
  53598. /** @ignore */
  53599. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53600. var defines = "";
  53601. if (this._scene.clipPlane) {
  53602. defines = "\n#define CLIPPLANE";
  53603. }
  53604. if (this._renderEffect && this._renderEffect.defines === defines) {
  53605. return;
  53606. }
  53607. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53608. };
  53609. /**
  53610. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53611. */
  53612. GPUParticleSystem.prototype.animate = function () {
  53613. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53614. this._actualFrame += this._timeDelta;
  53615. if (!this._stopped) {
  53616. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53617. this.stop();
  53618. }
  53619. }
  53620. };
  53621. /**
  53622. * Renders the particle system in its current state.
  53623. * @returns the current number of particles
  53624. */
  53625. GPUParticleSystem.prototype.render = function () {
  53626. if (!this._started) {
  53627. return 0;
  53628. }
  53629. this._recreateUpdateEffect();
  53630. this._recreateRenderEffect();
  53631. if (!this.isReady()) {
  53632. return 0;
  53633. }
  53634. if (this._currentRenderId === this._scene.getRenderId()) {
  53635. return 0;
  53636. }
  53637. this._currentRenderId = this._scene.getRenderId();
  53638. // Get everything ready to render
  53639. this._initialize();
  53640. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53641. // Enable update effect
  53642. this._engine.enableEffect(this._updateEffect);
  53643. this._engine.setState(false);
  53644. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53645. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53646. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53647. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53648. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53649. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53650. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53651. this._updateEffect.setDirectColor4("color1", this.color1);
  53652. this._updateEffect.setDirectColor4("color2", this.color2);
  53653. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53654. this._updateEffect.setVector3("gravity", this.gravity);
  53655. if (this.particleEmitterType) {
  53656. this.particleEmitterType.applyToShader(this._updateEffect);
  53657. }
  53658. var emitterWM;
  53659. if (this.emitter.position) {
  53660. var emitterMesh = this.emitter;
  53661. emitterWM = emitterMesh.getWorldMatrix();
  53662. }
  53663. else {
  53664. var emitterPosition = this.emitter;
  53665. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53666. }
  53667. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53668. // Bind source VAO
  53669. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53670. // Update
  53671. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53672. this._engine.setRasterizerState(false);
  53673. this._engine.beginTransformFeedback();
  53674. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53675. this._engine.endTransformFeedback();
  53676. this._engine.setRasterizerState(true);
  53677. this._engine.bindTransformFeedbackBuffer(null);
  53678. // Enable render effect
  53679. this._engine.enableEffect(this._renderEffect);
  53680. var viewMatrix = this._scene.getViewMatrix();
  53681. this._renderEffect.setMatrix("view", viewMatrix);
  53682. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53683. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53684. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53685. if (this._scene.clipPlane) {
  53686. var clipPlane = this._scene.clipPlane;
  53687. var invView = viewMatrix.clone();
  53688. invView.invert();
  53689. this._renderEffect.setMatrix("invView", invView);
  53690. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53691. }
  53692. // Draw order
  53693. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53694. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53695. }
  53696. else {
  53697. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53698. }
  53699. if (this.forceDepthWrite) {
  53700. this._engine.setDepthWrite(true);
  53701. }
  53702. // Bind source VAO
  53703. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53704. // Render
  53705. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53706. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53707. // Switch VAOs
  53708. this._targetIndex++;
  53709. if (this._targetIndex === 2) {
  53710. this._targetIndex = 0;
  53711. }
  53712. // Switch buffers
  53713. var tmpBuffer = this._sourceBuffer;
  53714. this._sourceBuffer = this._targetBuffer;
  53715. this._targetBuffer = tmpBuffer;
  53716. return this._currentActiveCount;
  53717. };
  53718. /**
  53719. * Rebuilds the particle system
  53720. */
  53721. GPUParticleSystem.prototype.rebuild = function () {
  53722. this._initialize(true);
  53723. };
  53724. GPUParticleSystem.prototype._releaseBuffers = function () {
  53725. if (this._buffer0) {
  53726. this._buffer0.dispose();
  53727. this._buffer0 = null;
  53728. }
  53729. if (this._buffer1) {
  53730. this._buffer1.dispose();
  53731. this._buffer1 = null;
  53732. }
  53733. if (this._spriteBuffer) {
  53734. this._spriteBuffer.dispose();
  53735. this._spriteBuffer = null;
  53736. }
  53737. };
  53738. GPUParticleSystem.prototype._releaseVAOs = function () {
  53739. if (!this._updateVAO) {
  53740. return;
  53741. }
  53742. for (var index = 0; index < this._updateVAO.length; index++) {
  53743. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53744. }
  53745. this._updateVAO = [];
  53746. for (var index = 0; index < this._renderVAO.length; index++) {
  53747. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53748. }
  53749. this._renderVAO = [];
  53750. };
  53751. /**
  53752. * Disposes the particle system and free the associated resources
  53753. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53754. */
  53755. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53756. if (disposeTexture === void 0) { disposeTexture = true; }
  53757. var index = this._scene.particleSystems.indexOf(this);
  53758. if (index > -1) {
  53759. this._scene.particleSystems.splice(index, 1);
  53760. }
  53761. this._releaseBuffers();
  53762. this._releaseVAOs();
  53763. if (this._randomTexture) {
  53764. this._randomTexture.dispose();
  53765. this._randomTexture = null;
  53766. }
  53767. if (disposeTexture && this.particleTexture) {
  53768. this.particleTexture.dispose();
  53769. this.particleTexture = null;
  53770. }
  53771. // Callback
  53772. this.onDisposeObservable.notifyObservers(this);
  53773. this.onDisposeObservable.clear();
  53774. };
  53775. /**
  53776. * Clones the particle system.
  53777. * @param name The name of the cloned object
  53778. * @param newEmitter The new emitter to use
  53779. * @returns the cloned particle system
  53780. */
  53781. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53782. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53783. BABYLON.Tools.DeepCopy(this, result);
  53784. if (newEmitter === undefined) {
  53785. newEmitter = this.emitter;
  53786. }
  53787. result.emitter = newEmitter;
  53788. if (this.particleTexture) {
  53789. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53790. }
  53791. return result;
  53792. };
  53793. /**
  53794. * Serializes the particle system to a JSON object.
  53795. * @returns the JSON object
  53796. */
  53797. GPUParticleSystem.prototype.serialize = function () {
  53798. var serializationObject = {};
  53799. serializationObject.name = this.name;
  53800. serializationObject.id = this.id;
  53801. // Emitter
  53802. if (this.emitter.position) {
  53803. var emitterMesh = this.emitter;
  53804. serializationObject.emitterId = emitterMesh.id;
  53805. }
  53806. else {
  53807. var emitterPosition = this.emitter;
  53808. serializationObject.emitter = emitterPosition.asArray();
  53809. }
  53810. serializationObject.capacity = this.getCapacity();
  53811. if (this.particleTexture) {
  53812. serializationObject.textureName = this.particleTexture.name;
  53813. }
  53814. // Animations
  53815. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53816. // Particle system
  53817. serializationObject.activeParticleCount = this.activeParticleCount;
  53818. serializationObject.randomTextureSize = this._randomTextureSize;
  53819. serializationObject.minSize = this.minSize;
  53820. serializationObject.maxSize = this.maxSize;
  53821. serializationObject.minEmitPower = this.minEmitPower;
  53822. serializationObject.maxEmitPower = this.maxEmitPower;
  53823. serializationObject.minLifeTime = this.minLifeTime;
  53824. serializationObject.maxLifeTime = this.maxLifeTime;
  53825. serializationObject.emitRate = this.emitRate;
  53826. serializationObject.gravity = this.gravity.asArray();
  53827. serializationObject.color1 = this.color1.asArray();
  53828. serializationObject.color2 = this.color2.asArray();
  53829. serializationObject.colorDead = this.colorDead.asArray();
  53830. serializationObject.updateSpeed = this.updateSpeed;
  53831. serializationObject.targetStopDuration = this.targetStopDuration;
  53832. serializationObject.blendMode = this.blendMode;
  53833. // Emitter
  53834. if (this.particleEmitterType) {
  53835. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53836. }
  53837. return serializationObject;
  53838. };
  53839. /**
  53840. * Parses a JSON object to create a GPU particle system.
  53841. * @param parsedParticleSystem The JSON object to parse
  53842. * @param scene The scene to create the particle system in
  53843. * @param rootUrl The root url to use to load external dependencies like texture
  53844. * @returns the parsed GPU particle system
  53845. */
  53846. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53847. var name = parsedParticleSystem.name;
  53848. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53849. if (parsedParticleSystem.id) {
  53850. particleSystem.id = parsedParticleSystem.id;
  53851. }
  53852. // Texture
  53853. if (parsedParticleSystem.textureName) {
  53854. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53855. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53856. }
  53857. // Emitter
  53858. if (parsedParticleSystem.emitterId) {
  53859. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53860. }
  53861. else {
  53862. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53863. }
  53864. // Animations
  53865. if (parsedParticleSystem.animations) {
  53866. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53867. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53868. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53869. }
  53870. }
  53871. // Particle system
  53872. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53873. particleSystem.minSize = parsedParticleSystem.minSize;
  53874. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53875. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53876. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53877. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53878. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53879. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53880. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53881. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53882. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53883. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53884. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53885. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53886. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53887. // Emitter
  53888. if (parsedParticleSystem.particleEmitterType) {
  53889. var emitterType = void 0;
  53890. switch (parsedParticleSystem.particleEmitterType.type) {
  53891. case "SphereEmitter":
  53892. emitterType = new BABYLON.SphereParticleEmitter();
  53893. break;
  53894. case "SphereDirectedParticleEmitter":
  53895. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53896. break;
  53897. case "ConeEmitter":
  53898. emitterType = new BABYLON.ConeParticleEmitter();
  53899. break;
  53900. case "BoxEmitter":
  53901. default:
  53902. emitterType = new BABYLON.BoxParticleEmitter();
  53903. break;
  53904. }
  53905. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53906. particleSystem.particleEmitterType = emitterType;
  53907. }
  53908. return particleSystem;
  53909. };
  53910. return GPUParticleSystem;
  53911. }());
  53912. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53913. })(BABYLON || (BABYLON = {}));
  53914. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53915. "use strict";
  53916. var BABYLON;
  53917. (function (BABYLON) {
  53918. /**
  53919. * Represents one particle of a solid particle system.
  53920. */
  53921. var SolidParticle = /** @class */ (function () {
  53922. /**
  53923. * Creates a Solid Particle object.
  53924. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53925. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53926. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53927. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53928. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53929. * @param shapeId (integer) is the model shape identifier in the SPS.
  53930. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53931. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53932. */
  53933. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53934. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53935. /**
  53936. * particle global index
  53937. */
  53938. this.idx = 0;
  53939. /**
  53940. * The color of the particle
  53941. */
  53942. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53943. /**
  53944. * The world space position of the particle.
  53945. */
  53946. this.position = BABYLON.Vector3.Zero();
  53947. /**
  53948. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53949. */
  53950. this.rotation = BABYLON.Vector3.Zero();
  53951. /**
  53952. * The scaling of the particle.
  53953. */
  53954. this.scaling = BABYLON.Vector3.One();
  53955. /**
  53956. * The uvs of the particle.
  53957. */
  53958. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53959. /**
  53960. * The current speed of the particle.
  53961. */
  53962. this.velocity = BABYLON.Vector3.Zero();
  53963. /**
  53964. * The pivot point in the particle local space.
  53965. */
  53966. this.pivot = BABYLON.Vector3.Zero();
  53967. /**
  53968. * Must the particle be translated from its pivot point in its local space ?
  53969. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53970. * Default : false
  53971. */
  53972. this.translateFromPivot = false;
  53973. /**
  53974. * Is the particle active or not ?
  53975. */
  53976. this.alive = true;
  53977. /**
  53978. * Is the particle visible or not ?
  53979. */
  53980. this.isVisible = true;
  53981. /**
  53982. * Index of this particle in the global "positions" array (Internal use)
  53983. */
  53984. this._pos = 0;
  53985. /**
  53986. * Index of this particle in the global "indices" array (Internal use)
  53987. */
  53988. this._ind = 0;
  53989. /**
  53990. * ModelShape id of this particle
  53991. */
  53992. this.shapeId = 0;
  53993. /**
  53994. * Index of the particle in its shape id (Internal use)
  53995. */
  53996. this.idxInShape = 0;
  53997. /**
  53998. * Still set as invisible in order to skip useless computations (Internal use)
  53999. */
  54000. this._stillInvisible = false;
  54001. /**
  54002. * Last computed particle rotation matrix
  54003. */
  54004. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  54005. /**
  54006. * Parent particle Id, if any.
  54007. * Default null.
  54008. */
  54009. this.parentId = null;
  54010. /**
  54011. * Internal global position in the SPS.
  54012. */
  54013. this._globalPosition = BABYLON.Vector3.Zero();
  54014. this.idx = particleIndex;
  54015. this._pos = positionIndex;
  54016. this._ind = indiceIndex;
  54017. this._model = model;
  54018. this.shapeId = shapeId;
  54019. this.idxInShape = idxInShape;
  54020. this._sps = sps;
  54021. if (modelBoundingInfo) {
  54022. this._modelBoundingInfo = modelBoundingInfo;
  54023. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  54024. }
  54025. }
  54026. Object.defineProperty(SolidParticle.prototype, "scale", {
  54027. /**
  54028. * Legacy support, changed scale to scaling
  54029. */
  54030. get: function () {
  54031. return this.scaling;
  54032. },
  54033. /**
  54034. * Legacy support, changed scale to scaling
  54035. */
  54036. set: function (scale) {
  54037. this.scaling = scale;
  54038. },
  54039. enumerable: true,
  54040. configurable: true
  54041. });
  54042. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54043. /**
  54044. * Legacy support, changed quaternion to rotationQuaternion
  54045. */
  54046. get: function () {
  54047. return this.rotationQuaternion;
  54048. },
  54049. /**
  54050. * Legacy support, changed quaternion to rotationQuaternion
  54051. */
  54052. set: function (q) {
  54053. this.rotationQuaternion = q;
  54054. },
  54055. enumerable: true,
  54056. configurable: true
  54057. });
  54058. /**
  54059. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54060. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54061. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54062. * @returns true if it intersects
  54063. */
  54064. SolidParticle.prototype.intersectsMesh = function (target) {
  54065. if (!this._boundingInfo || !target._boundingInfo) {
  54066. return false;
  54067. }
  54068. if (this._sps._bSphereOnly) {
  54069. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54070. }
  54071. return this._boundingInfo.intersects(target._boundingInfo, false);
  54072. };
  54073. return SolidParticle;
  54074. }());
  54075. BABYLON.SolidParticle = SolidParticle;
  54076. /**
  54077. * Represents the shape of the model used by one particle of a solid particle system.
  54078. * SPS internal tool, don't use it manually.
  54079. */
  54080. var ModelShape = /** @class */ (function () {
  54081. /**
  54082. * 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.
  54083. * SPS internal tool, don't use it manually.
  54084. * @ignore
  54085. */
  54086. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54087. /**
  54088. * length of the shape in the model indices array (internal use)
  54089. */
  54090. this._indicesLength = 0;
  54091. this.shapeID = id;
  54092. this._shape = shape;
  54093. this._indicesLength = indicesLength;
  54094. this._shapeUV = shapeUV;
  54095. this._positionFunction = posFunction;
  54096. this._vertexFunction = vtxFunction;
  54097. }
  54098. return ModelShape;
  54099. }());
  54100. BABYLON.ModelShape = ModelShape;
  54101. /**
  54102. * Represents a Depth Sorted Particle in the solid particle system.
  54103. */
  54104. var DepthSortedParticle = /** @class */ (function () {
  54105. function DepthSortedParticle() {
  54106. /**
  54107. * Index of the particle in the "indices" array
  54108. */
  54109. this.ind = 0;
  54110. /**
  54111. * Length of the particle shape in the "indices" array
  54112. */
  54113. this.indicesLength = 0;
  54114. /**
  54115. * Squared distance from the particle to the camera
  54116. */
  54117. this.sqDistance = 0.0;
  54118. }
  54119. return DepthSortedParticle;
  54120. }());
  54121. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54122. })(BABYLON || (BABYLON = {}));
  54123. //# sourceMappingURL=babylon.solidParticle.js.map
  54124. "use strict";
  54125. var BABYLON;
  54126. (function (BABYLON) {
  54127. /**
  54128. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54129. *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.
  54130. * The SPS is also a particle system. It provides some methods to manage the particles.
  54131. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54132. *
  54133. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54134. */
  54135. var SolidParticleSystem = /** @class */ (function () {
  54136. /**
  54137. * Creates a SPS (Solid Particle System) object.
  54138. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54139. * @param scene (Scene) is the scene in which the SPS is added.
  54140. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54141. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54142. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54143. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54144. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54145. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54146. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54147. */
  54148. function SolidParticleSystem(name, scene, options) {
  54149. /**
  54150. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54151. * Example : var p = SPS.particles[i];
  54152. */
  54153. this.particles = new Array();
  54154. /**
  54155. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54156. */
  54157. this.nbParticles = 0;
  54158. /**
  54159. * If the particles must ever face the camera (default false). Useful for planar particles.
  54160. */
  54161. this.billboard = false;
  54162. /**
  54163. * Recompute normals when adding a shape
  54164. */
  54165. this.recomputeNormals = true;
  54166. /**
  54167. * This a counter ofr your own usage. It's not set by any SPS functions.
  54168. */
  54169. this.counter = 0;
  54170. /**
  54171. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54172. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54173. */
  54174. this.vars = {};
  54175. /**
  54176. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54177. */
  54178. this._bSphereOnly = false;
  54179. /**
  54180. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54181. */
  54182. this._bSphereRadiusFactor = 1.0;
  54183. this._positions = new Array();
  54184. this._indices = new Array();
  54185. this._normals = new Array();
  54186. this._colors = new Array();
  54187. this._uvs = new Array();
  54188. this._index = 0; // indices index
  54189. this._updatable = true;
  54190. this._pickable = false;
  54191. this._isVisibilityBoxLocked = false;
  54192. this._alwaysVisible = false;
  54193. this._depthSort = false;
  54194. this._shapeCounter = 0;
  54195. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54196. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54197. this._computeParticleColor = true;
  54198. this._computeParticleTexture = true;
  54199. this._computeParticleRotation = true;
  54200. this._computeParticleVertex = false;
  54201. this._computeBoundingBox = false;
  54202. this._depthSortParticles = true;
  54203. this._cam_axisZ = BABYLON.Vector3.Zero();
  54204. this._cam_axisY = BABYLON.Vector3.Zero();
  54205. this._cam_axisX = BABYLON.Vector3.Zero();
  54206. this._axisZ = BABYLON.Axis.Z;
  54207. this._camDir = BABYLON.Vector3.Zero();
  54208. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54209. this._rotMatrix = new BABYLON.Matrix();
  54210. this._invertMatrix = new BABYLON.Matrix();
  54211. this._rotated = BABYLON.Vector3.Zero();
  54212. this._quaternion = new BABYLON.Quaternion();
  54213. this._vertex = BABYLON.Vector3.Zero();
  54214. this._normal = BABYLON.Vector3.Zero();
  54215. this._yaw = 0.0;
  54216. this._pitch = 0.0;
  54217. this._roll = 0.0;
  54218. this._halfroll = 0.0;
  54219. this._halfpitch = 0.0;
  54220. this._halfyaw = 0.0;
  54221. this._sinRoll = 0.0;
  54222. this._cosRoll = 0.0;
  54223. this._sinPitch = 0.0;
  54224. this._cosPitch = 0.0;
  54225. this._sinYaw = 0.0;
  54226. this._cosYaw = 0.0;
  54227. this._mustUnrotateFixedNormals = false;
  54228. this._minimum = BABYLON.Vector3.Zero();
  54229. this._maximum = BABYLON.Vector3.Zero();
  54230. this._minBbox = BABYLON.Vector3.Zero();
  54231. this._maxBbox = BABYLON.Vector3.Zero();
  54232. this._particlesIntersect = false;
  54233. this._depthSortFunction = function (p1, p2) {
  54234. return (p2.sqDistance - p1.sqDistance);
  54235. };
  54236. this._needs32Bits = false;
  54237. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54238. this._scaledPivot = BABYLON.Vector3.Zero();
  54239. this._particleHasParent = false;
  54240. this.name = name;
  54241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54242. this._camera = scene.activeCamera;
  54243. this._pickable = options ? options.isPickable : false;
  54244. this._depthSort = options ? options.enableDepthSort : false;
  54245. this._particlesIntersect = options ? options.particleIntersection : false;
  54246. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54247. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54248. if (options && options.updatable) {
  54249. this._updatable = options.updatable;
  54250. }
  54251. else {
  54252. this._updatable = true;
  54253. }
  54254. if (this._pickable) {
  54255. this.pickedParticles = [];
  54256. }
  54257. if (this._depthSort) {
  54258. this.depthSortedParticles = [];
  54259. }
  54260. }
  54261. /**
  54262. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54263. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54264. * @returns the created mesh
  54265. */
  54266. SolidParticleSystem.prototype.buildMesh = function () {
  54267. if (this.nbParticles === 0) {
  54268. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54269. this.addShape(triangle, 1);
  54270. triangle.dispose();
  54271. }
  54272. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54273. this._positions32 = new Float32Array(this._positions);
  54274. this._uvs32 = new Float32Array(this._uvs);
  54275. this._colors32 = new Float32Array(this._colors);
  54276. if (this.recomputeNormals) {
  54277. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54278. }
  54279. this._normals32 = new Float32Array(this._normals);
  54280. this._fixedNormal32 = new Float32Array(this._normals);
  54281. if (this._mustUnrotateFixedNormals) {
  54282. this._unrotateFixedNormals();
  54283. }
  54284. var vertexData = new BABYLON.VertexData();
  54285. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54286. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54287. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54288. if (this._uvs32) {
  54289. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54290. ;
  54291. }
  54292. if (this._colors32) {
  54293. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54294. }
  54295. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54296. vertexData.applyToMesh(mesh, this._updatable);
  54297. this.mesh = mesh;
  54298. this.mesh.isPickable = this._pickable;
  54299. // free memory
  54300. if (!this._depthSort) {
  54301. this._indices = null;
  54302. }
  54303. this._positions = null;
  54304. this._normals = null;
  54305. this._uvs = null;
  54306. this._colors = null;
  54307. if (!this._updatable) {
  54308. this.particles.length = 0;
  54309. }
  54310. return mesh;
  54311. };
  54312. /**
  54313. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54314. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54315. * Thus the particles generated from `digest()` have their property `position` set yet.
  54316. * @param mesh ( Mesh ) is the mesh to be digested
  54317. * @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
  54318. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54319. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54320. * @returns the current SPS
  54321. */
  54322. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54323. var size = (options && options.facetNb) || 1;
  54324. var number = (options && options.number) || 0;
  54325. var delta = (options && options.delta) || 0;
  54326. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54327. var meshInd = mesh.getIndices();
  54328. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54329. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54330. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54331. var f = 0; // facet counter
  54332. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54333. // compute size from number
  54334. if (number) {
  54335. number = (number > totalFacets) ? totalFacets : number;
  54336. size = Math.round(totalFacets / number);
  54337. delta = 0;
  54338. }
  54339. else {
  54340. size = (size > totalFacets) ? totalFacets : size;
  54341. }
  54342. var facetPos = []; // submesh positions
  54343. var facetInd = []; // submesh indices
  54344. var facetUV = []; // submesh UV
  54345. var facetCol = []; // submesh colors
  54346. var barycenter = BABYLON.Vector3.Zero();
  54347. var sizeO = size;
  54348. while (f < totalFacets) {
  54349. size = sizeO + Math.floor((1 + delta) * Math.random());
  54350. if (f > totalFacets - size) {
  54351. size = totalFacets - f;
  54352. }
  54353. // reset temp arrays
  54354. facetPos.length = 0;
  54355. facetInd.length = 0;
  54356. facetUV.length = 0;
  54357. facetCol.length = 0;
  54358. // iterate over "size" facets
  54359. var fi = 0;
  54360. for (var j = f * 3; j < (f + size) * 3; j++) {
  54361. facetInd.push(fi);
  54362. var i = meshInd[j];
  54363. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54364. if (meshUV) {
  54365. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54366. }
  54367. if (meshCol) {
  54368. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54369. }
  54370. fi++;
  54371. }
  54372. // create a model shape for each single particle
  54373. var idx = this.nbParticles;
  54374. var shape = this._posToShape(facetPos);
  54375. var shapeUV = this._uvsToShapeUV(facetUV);
  54376. // compute the barycenter of the shape
  54377. var v;
  54378. for (v = 0; v < shape.length; v++) {
  54379. barycenter.addInPlace(shape[v]);
  54380. }
  54381. barycenter.scaleInPlace(1 / shape.length);
  54382. // shift the shape from its barycenter to the origin
  54383. for (v = 0; v < shape.length; v++) {
  54384. shape[v].subtractInPlace(barycenter);
  54385. }
  54386. var bInfo;
  54387. if (this._particlesIntersect) {
  54388. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54389. }
  54390. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54391. // add the particle in the SPS
  54392. var currentPos = this._positions.length;
  54393. var currentInd = this._indices.length;
  54394. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54395. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54396. // initialize the particle position
  54397. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54398. this._index += shape.length;
  54399. idx++;
  54400. this.nbParticles++;
  54401. this._shapeCounter++;
  54402. f += size;
  54403. }
  54404. return this;
  54405. };
  54406. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54407. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54408. var index = 0;
  54409. var idx = 0;
  54410. for (var p = 0; p < this.particles.length; p++) {
  54411. this._particle = this.particles[p];
  54412. this._shape = this._particle._model._shape;
  54413. if (this._particle.rotationQuaternion) {
  54414. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54415. }
  54416. else {
  54417. this._yaw = this._particle.rotation.y;
  54418. this._pitch = this._particle.rotation.x;
  54419. this._roll = this._particle.rotation.z;
  54420. this._quaternionRotationYPR();
  54421. }
  54422. this._quaternionToRotationMatrix();
  54423. this._rotMatrix.invertToRef(this._invertMatrix);
  54424. for (var pt = 0; pt < this._shape.length; pt++) {
  54425. idx = index + pt * 3;
  54426. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54427. this._fixedNormal32[idx] = this._normal.x;
  54428. this._fixedNormal32[idx + 1] = this._normal.y;
  54429. this._fixedNormal32[idx + 2] = this._normal.z;
  54430. }
  54431. index = idx + 3;
  54432. }
  54433. };
  54434. //reset copy
  54435. SolidParticleSystem.prototype._resetCopy = function () {
  54436. this._copy.position.x = 0;
  54437. this._copy.position.y = 0;
  54438. this._copy.position.z = 0;
  54439. this._copy.rotation.x = 0;
  54440. this._copy.rotation.y = 0;
  54441. this._copy.rotation.z = 0;
  54442. this._copy.rotationQuaternion = null;
  54443. this._copy.scaling.x = 1.0;
  54444. this._copy.scaling.y = 1.0;
  54445. this._copy.scaling.z = 1.0;
  54446. this._copy.uvs.x = 0;
  54447. this._copy.uvs.y = 0;
  54448. this._copy.uvs.z = 1.0;
  54449. this._copy.uvs.w = 1.0;
  54450. this._copy.color = null;
  54451. this._copy.translateFromPivot = false;
  54452. };
  54453. // _meshBuilder : inserts the shape model in the global SPS mesh
  54454. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54455. var i;
  54456. var u = 0;
  54457. var c = 0;
  54458. var n = 0;
  54459. this._resetCopy();
  54460. if (options && options.positionFunction) {
  54461. options.positionFunction(this._copy, idx, idxInShape);
  54462. this._mustUnrotateFixedNormals = true;
  54463. }
  54464. if (this._copy.rotationQuaternion) {
  54465. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54466. }
  54467. else {
  54468. this._yaw = this._copy.rotation.y;
  54469. this._pitch = this._copy.rotation.x;
  54470. this._roll = this._copy.rotation.z;
  54471. this._quaternionRotationYPR();
  54472. }
  54473. this._quaternionToRotationMatrix();
  54474. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54475. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54476. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54477. if (this._copy.translateFromPivot) {
  54478. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54479. }
  54480. else {
  54481. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54482. }
  54483. for (i = 0; i < shape.length; i++) {
  54484. this._vertex.x = shape[i].x;
  54485. this._vertex.y = shape[i].y;
  54486. this._vertex.z = shape[i].z;
  54487. if (options && options.vertexFunction) {
  54488. options.vertexFunction(this._copy, this._vertex, i);
  54489. }
  54490. this._vertex.x *= this._copy.scaling.x;
  54491. this._vertex.y *= this._copy.scaling.y;
  54492. this._vertex.z *= this._copy.scaling.z;
  54493. this._vertex.x -= this._scaledPivot.x;
  54494. this._vertex.y -= this._scaledPivot.y;
  54495. this._vertex.z -= this._scaledPivot.z;
  54496. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54497. this._rotated.addInPlace(this._pivotBackTranslation);
  54498. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54499. if (meshUV) {
  54500. 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);
  54501. u += 2;
  54502. }
  54503. if (this._copy.color) {
  54504. this._color = this._copy.color;
  54505. }
  54506. else if (meshCol && meshCol[c] !== undefined) {
  54507. this._color.r = meshCol[c];
  54508. this._color.g = meshCol[c + 1];
  54509. this._color.b = meshCol[c + 2];
  54510. this._color.a = meshCol[c + 3];
  54511. }
  54512. else {
  54513. this._color.r = 1.0;
  54514. this._color.g = 1.0;
  54515. this._color.b = 1.0;
  54516. this._color.a = 1.0;
  54517. }
  54518. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54519. c += 4;
  54520. if (!this.recomputeNormals && meshNor) {
  54521. this._normal.x = meshNor[n];
  54522. this._normal.y = meshNor[n + 1];
  54523. this._normal.z = meshNor[n + 2];
  54524. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54525. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54526. n += 3;
  54527. }
  54528. }
  54529. for (i = 0; i < meshInd.length; i++) {
  54530. var current_ind = p + meshInd[i];
  54531. indices.push(current_ind);
  54532. if (current_ind > 65535) {
  54533. this._needs32Bits = true;
  54534. }
  54535. }
  54536. if (this._pickable) {
  54537. var nbfaces = meshInd.length / 3;
  54538. for (i = 0; i < nbfaces; i++) {
  54539. this.pickedParticles.push({ idx: idx, faceId: i });
  54540. }
  54541. }
  54542. if (this._depthSort) {
  54543. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54544. }
  54545. return this._copy;
  54546. };
  54547. // returns a shape array from positions array
  54548. SolidParticleSystem.prototype._posToShape = function (positions) {
  54549. var shape = [];
  54550. for (var i = 0; i < positions.length; i += 3) {
  54551. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54552. }
  54553. return shape;
  54554. };
  54555. // returns a shapeUV array from a Vector4 uvs
  54556. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54557. var shapeUV = [];
  54558. if (uvs) {
  54559. for (var i = 0; i < uvs.length; i++)
  54560. shapeUV.push(uvs[i]);
  54561. }
  54562. return shapeUV;
  54563. };
  54564. // adds a new particle object in the particles array
  54565. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54566. if (bInfo === void 0) { bInfo = null; }
  54567. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54568. this.particles.push(sp);
  54569. return sp;
  54570. };
  54571. /**
  54572. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54573. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54574. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54575. * @param nb (positive integer) the number of particles to be created from this model
  54576. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54577. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54578. * @returns the number of shapes in the system
  54579. */
  54580. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54581. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54582. var meshInd = mesh.getIndices();
  54583. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54584. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54585. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54586. var bbInfo;
  54587. if (this._particlesIntersect) {
  54588. bbInfo = mesh.getBoundingInfo();
  54589. }
  54590. var shape = this._posToShape(meshPos);
  54591. var shapeUV = this._uvsToShapeUV(meshUV);
  54592. var posfunc = options ? options.positionFunction : null;
  54593. var vtxfunc = options ? options.vertexFunction : null;
  54594. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54595. // particles
  54596. var sp;
  54597. var currentCopy;
  54598. var idx = this.nbParticles;
  54599. for (var i = 0; i < nb; i++) {
  54600. var currentPos = this._positions.length;
  54601. var currentInd = this._indices.length;
  54602. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54603. if (this._updatable) {
  54604. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54605. sp.position.copyFrom(currentCopy.position);
  54606. sp.rotation.copyFrom(currentCopy.rotation);
  54607. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54608. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54609. }
  54610. if (currentCopy.color && sp.color) {
  54611. sp.color.copyFrom(currentCopy.color);
  54612. }
  54613. sp.scaling.copyFrom(currentCopy.scaling);
  54614. sp.uvs.copyFrom(currentCopy.uvs);
  54615. }
  54616. this._index += shape.length;
  54617. idx++;
  54618. }
  54619. this.nbParticles += nb;
  54620. this._shapeCounter++;
  54621. return this._shapeCounter - 1;
  54622. };
  54623. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54624. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54625. this._resetCopy();
  54626. if (particle._model._positionFunction) {
  54627. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54628. }
  54629. if (this._copy.rotationQuaternion) {
  54630. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54631. }
  54632. else {
  54633. this._yaw = this._copy.rotation.y;
  54634. this._pitch = this._copy.rotation.x;
  54635. this._roll = this._copy.rotation.z;
  54636. this._quaternionRotationYPR();
  54637. }
  54638. this._quaternionToRotationMatrix();
  54639. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54640. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54641. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54642. if (this._copy.translateFromPivot) {
  54643. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54644. }
  54645. else {
  54646. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54647. }
  54648. this._shape = particle._model._shape;
  54649. for (var pt = 0; pt < this._shape.length; pt++) {
  54650. this._vertex.x = this._shape[pt].x;
  54651. this._vertex.y = this._shape[pt].y;
  54652. this._vertex.z = this._shape[pt].z;
  54653. if (particle._model._vertexFunction) {
  54654. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54655. }
  54656. this._vertex.x *= this._copy.scaling.x;
  54657. this._vertex.y *= this._copy.scaling.y;
  54658. this._vertex.z *= this._copy.scaling.z;
  54659. this._vertex.x -= this._scaledPivot.x;
  54660. this._vertex.y -= this._scaledPivot.y;
  54661. this._vertex.z -= this._scaledPivot.z;
  54662. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54663. this._rotated.addInPlace(this._pivotBackTranslation);
  54664. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54665. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54666. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54667. }
  54668. particle.position.x = 0.0;
  54669. particle.position.y = 0.0;
  54670. particle.position.z = 0.0;
  54671. particle.rotation.x = 0.0;
  54672. particle.rotation.y = 0.0;
  54673. particle.rotation.z = 0.0;
  54674. particle.rotationQuaternion = null;
  54675. particle.scaling.x = 1.0;
  54676. particle.scaling.y = 1.0;
  54677. particle.scaling.z = 1.0;
  54678. particle.uvs.x = 0.0;
  54679. particle.uvs.y = 0.0;
  54680. particle.uvs.z = 1.0;
  54681. particle.uvs.w = 1.0;
  54682. particle.pivot.x = 0.0;
  54683. particle.pivot.y = 0.0;
  54684. particle.pivot.z = 0.0;
  54685. particle.translateFromPivot = false;
  54686. particle.parentId = null;
  54687. };
  54688. /**
  54689. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54690. * @returns the SPS.
  54691. */
  54692. SolidParticleSystem.prototype.rebuildMesh = function () {
  54693. for (var p = 0; p < this.particles.length; p++) {
  54694. this._rebuildParticle(this.particles[p]);
  54695. }
  54696. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54697. return this;
  54698. };
  54699. /**
  54700. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54701. * This method calls `updateParticle()` for each particle of the SPS.
  54702. * For an animated SPS, it is usually called within the render loop.
  54703. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54704. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54705. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54706. * @returns the SPS.
  54707. */
  54708. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54709. if (start === void 0) { start = 0; }
  54710. if (end === void 0) { end = this.nbParticles - 1; }
  54711. if (update === void 0) { update = true; }
  54712. if (!this._updatable) {
  54713. return this;
  54714. }
  54715. // custom beforeUpdate
  54716. this.beforeUpdateParticles(start, end, update);
  54717. this._cam_axisX.x = 1.0;
  54718. this._cam_axisX.y = 0.0;
  54719. this._cam_axisX.z = 0.0;
  54720. this._cam_axisY.x = 0.0;
  54721. this._cam_axisY.y = 1.0;
  54722. this._cam_axisY.z = 0.0;
  54723. this._cam_axisZ.x = 0.0;
  54724. this._cam_axisZ.y = 0.0;
  54725. this._cam_axisZ.z = 1.0;
  54726. // cases when the World Matrix is to be computed first
  54727. if (this.billboard || this._depthSort) {
  54728. this.mesh.computeWorldMatrix(true);
  54729. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54730. }
  54731. // if the particles will always face the camera
  54732. if (this.billboard) {
  54733. // compute the camera position and un-rotate it by the current mesh rotation
  54734. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54735. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54736. this._cam_axisZ.normalize();
  54737. // same for camera up vector extracted from the cam view matrix
  54738. var view = this._camera.getViewMatrix(true);
  54739. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54740. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54741. this._cam_axisY.normalize();
  54742. this._cam_axisX.normalize();
  54743. }
  54744. // if depthSort, compute the camera global position in the mesh local system
  54745. if (this._depthSort) {
  54746. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54747. }
  54748. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54749. var idx = 0; // current position index in the global array positions32
  54750. var index = 0; // position start index in the global array positions32 of the current particle
  54751. var colidx = 0; // current color index in the global array colors32
  54752. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54753. var uvidx = 0; // current uv index in the global array uvs32
  54754. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54755. var pt = 0; // current index in the particle model shape
  54756. if (this.mesh.isFacetDataEnabled) {
  54757. this._computeBoundingBox = true;
  54758. }
  54759. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54760. if (this._computeBoundingBox) {
  54761. if (start == 0 && end == this.nbParticles - 1) {
  54762. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54763. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54764. }
  54765. else {
  54766. if (this.mesh._boundingInfo) {
  54767. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54768. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54769. }
  54770. }
  54771. }
  54772. // particle loop
  54773. index = this.particles[start]._pos;
  54774. var vpos = (index / 3) | 0;
  54775. colorIndex = vpos * 4;
  54776. uvIndex = vpos * 2;
  54777. for (var p = start; p <= end; p++) {
  54778. this._particle = this.particles[p];
  54779. this._shape = this._particle._model._shape;
  54780. this._shapeUV = this._particle._model._shapeUV;
  54781. // call to custom user function to update the particle properties
  54782. this.updateParticle(this._particle);
  54783. // camera-particle distance for depth sorting
  54784. if (this._depthSort && this._depthSortParticles) {
  54785. var dsp = this.depthSortedParticles[p];
  54786. dsp.ind = this._particle._ind;
  54787. dsp.indicesLength = this._particle._model._indicesLength;
  54788. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54789. }
  54790. // skip the computations for inactive or already invisible particles
  54791. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54792. // increment indexes for the next particle
  54793. pt = this._shape.length;
  54794. index += pt * 3;
  54795. colorIndex += pt * 4;
  54796. uvIndex += pt * 2;
  54797. continue;
  54798. }
  54799. if (this._particle.isVisible) {
  54800. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54801. this._particleHasParent = (this._particle.parentId !== null);
  54802. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54803. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54804. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54805. // particle rotation matrix
  54806. if (this.billboard) {
  54807. this._particle.rotation.x = 0.0;
  54808. this._particle.rotation.y = 0.0;
  54809. }
  54810. if (this._computeParticleRotation || this.billboard) {
  54811. if (this._particle.rotationQuaternion) {
  54812. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54813. }
  54814. else {
  54815. this._yaw = this._particle.rotation.y;
  54816. this._pitch = this._particle.rotation.x;
  54817. this._roll = this._particle.rotation.z;
  54818. this._quaternionRotationYPR();
  54819. }
  54820. this._quaternionToRotationMatrix();
  54821. }
  54822. if (this._particleHasParent) {
  54823. this._parent = this.particles[this._particle.parentId];
  54824. 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];
  54825. 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];
  54826. 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];
  54827. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54828. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54829. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54830. if (this._computeParticleRotation || this.billboard) {
  54831. 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];
  54832. 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];
  54833. 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];
  54834. 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];
  54835. 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];
  54836. 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];
  54837. 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];
  54838. 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];
  54839. 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];
  54840. }
  54841. }
  54842. else {
  54843. this._particle._globalPosition.x = this._particle.position.x;
  54844. this._particle._globalPosition.y = this._particle.position.y;
  54845. this._particle._globalPosition.z = this._particle.position.z;
  54846. if (this._computeParticleRotation || this.billboard) {
  54847. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54848. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54849. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54850. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54851. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54852. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54853. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54854. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54855. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54856. }
  54857. }
  54858. if (this._particle.translateFromPivot) {
  54859. this._pivotBackTranslation.x = 0.0;
  54860. this._pivotBackTranslation.y = 0.0;
  54861. this._pivotBackTranslation.z = 0.0;
  54862. }
  54863. else {
  54864. this._pivotBackTranslation.x = this._scaledPivot.x;
  54865. this._pivotBackTranslation.y = this._scaledPivot.y;
  54866. this._pivotBackTranslation.z = this._scaledPivot.z;
  54867. }
  54868. // particle vertex loop
  54869. for (pt = 0; pt < this._shape.length; pt++) {
  54870. idx = index + pt * 3;
  54871. colidx = colorIndex + pt * 4;
  54872. uvidx = uvIndex + pt * 2;
  54873. this._vertex.x = this._shape[pt].x;
  54874. this._vertex.y = this._shape[pt].y;
  54875. this._vertex.z = this._shape[pt].z;
  54876. if (this._computeParticleVertex) {
  54877. this.updateParticleVertex(this._particle, this._vertex, pt);
  54878. }
  54879. // positions
  54880. this._vertex.x *= this._particle.scaling.x;
  54881. this._vertex.y *= this._particle.scaling.y;
  54882. this._vertex.z *= this._particle.scaling.z;
  54883. this._vertex.x -= this._scaledPivot.x;
  54884. this._vertex.y -= this._scaledPivot.y;
  54885. this._vertex.z -= this._scaledPivot.z;
  54886. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54887. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54888. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54889. this._rotated.x += this._pivotBackTranslation.x;
  54890. this._rotated.y += this._pivotBackTranslation.y;
  54891. this._rotated.z += this._pivotBackTranslation.z;
  54892. 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;
  54893. 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;
  54894. 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;
  54895. if (this._computeBoundingBox) {
  54896. if (this._positions32[idx] < this._minimum.x) {
  54897. this._minimum.x = this._positions32[idx];
  54898. }
  54899. if (this._positions32[idx] > this._maximum.x) {
  54900. this._maximum.x = this._positions32[idx];
  54901. }
  54902. if (this._positions32[idx + 1] < this._minimum.y) {
  54903. this._minimum.y = this._positions32[idx + 1];
  54904. }
  54905. if (this._positions32[idx + 1] > this._maximum.y) {
  54906. this._maximum.y = this._positions32[idx + 1];
  54907. }
  54908. if (this._positions32[idx + 2] < this._minimum.z) {
  54909. this._minimum.z = this._positions32[idx + 2];
  54910. }
  54911. if (this._positions32[idx + 2] > this._maximum.z) {
  54912. this._maximum.z = this._positions32[idx + 2];
  54913. }
  54914. }
  54915. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54916. if (!this._computeParticleVertex) {
  54917. this._normal.x = this._fixedNormal32[idx];
  54918. this._normal.y = this._fixedNormal32[idx + 1];
  54919. this._normal.z = this._fixedNormal32[idx + 2];
  54920. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54921. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54922. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54923. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54924. 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;
  54925. 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;
  54926. }
  54927. if (this._computeParticleColor && this._particle.color) {
  54928. this._colors32[colidx] = this._particle.color.r;
  54929. this._colors32[colidx + 1] = this._particle.color.g;
  54930. this._colors32[colidx + 2] = this._particle.color.b;
  54931. this._colors32[colidx + 3] = this._particle.color.a;
  54932. }
  54933. if (this._computeParticleTexture) {
  54934. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54935. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54936. }
  54937. }
  54938. }
  54939. else {
  54940. this._particle._stillInvisible = true; // mark the particle as invisible
  54941. for (pt = 0; pt < this._shape.length; pt++) {
  54942. idx = index + pt * 3;
  54943. colidx = colorIndex + pt * 4;
  54944. uvidx = uvIndex + pt * 2;
  54945. this._positions32[idx] = 0.0;
  54946. this._positions32[idx + 1] = 0.0;
  54947. this._positions32[idx + 2] = 0.0;
  54948. this._normals32[idx] = 0.0;
  54949. this._normals32[idx + 1] = 0.0;
  54950. this._normals32[idx + 2] = 0.0;
  54951. if (this._computeParticleColor && this._particle.color) {
  54952. this._colors32[colidx] = this._particle.color.r;
  54953. this._colors32[colidx + 1] = this._particle.color.g;
  54954. this._colors32[colidx + 2] = this._particle.color.b;
  54955. this._colors32[colidx + 3] = this._particle.color.a;
  54956. }
  54957. if (this._computeParticleTexture) {
  54958. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54959. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54960. }
  54961. }
  54962. }
  54963. // if the particle intersections must be computed : update the bbInfo
  54964. if (this._particlesIntersect) {
  54965. var bInfo = this._particle._boundingInfo;
  54966. var bBox = bInfo.boundingBox;
  54967. var bSphere = bInfo.boundingSphere;
  54968. if (!this._bSphereOnly) {
  54969. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54970. for (var b = 0; b < bBox.vectors.length; b++) {
  54971. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54972. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54973. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54974. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54975. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54976. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54977. 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;
  54978. 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;
  54979. 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;
  54980. }
  54981. bBox._update(this.mesh._worldMatrix);
  54982. }
  54983. // place and scale the particle bouding sphere in the SPS local system, then update it
  54984. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54985. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54986. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54987. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54988. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54989. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54990. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54991. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54992. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54993. 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));
  54994. bSphere._update(this.mesh._worldMatrix);
  54995. }
  54996. // increment indexes for the next particle
  54997. index = idx + 3;
  54998. colorIndex = colidx + 4;
  54999. uvIndex = uvidx + 2;
  55000. }
  55001. // if the VBO must be updated
  55002. if (update) {
  55003. if (this._computeParticleColor) {
  55004. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55005. }
  55006. if (this._computeParticleTexture) {
  55007. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55008. }
  55009. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55010. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  55011. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  55012. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55013. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  55014. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  55015. for (var i = 0; i < this._normals32.length; i++) {
  55016. this._fixedNormal32[i] = this._normals32[i];
  55017. }
  55018. }
  55019. if (!this.mesh.areNormalsFrozen) {
  55020. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55021. }
  55022. }
  55023. if (this._depthSort && this._depthSortParticles) {
  55024. this.depthSortedParticles.sort(this._depthSortFunction);
  55025. var dspl = this.depthSortedParticles.length;
  55026. var sorted = 0;
  55027. var lind = 0;
  55028. var sind = 0;
  55029. var sid = 0;
  55030. for (sorted = 0; sorted < dspl; sorted++) {
  55031. lind = this.depthSortedParticles[sorted].indicesLength;
  55032. sind = this.depthSortedParticles[sorted].ind;
  55033. for (var i = 0; i < lind; i++) {
  55034. this._indices32[sid] = this._indices[sind + i];
  55035. sid++;
  55036. }
  55037. }
  55038. this.mesh.updateIndices(this._indices32);
  55039. }
  55040. }
  55041. if (this._computeBoundingBox) {
  55042. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55043. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55044. }
  55045. this.afterUpdateParticles(start, end, update);
  55046. return this;
  55047. };
  55048. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55049. this._halfroll = this._roll * 0.5;
  55050. this._halfpitch = this._pitch * 0.5;
  55051. this._halfyaw = this._yaw * 0.5;
  55052. this._sinRoll = Math.sin(this._halfroll);
  55053. this._cosRoll = Math.cos(this._halfroll);
  55054. this._sinPitch = Math.sin(this._halfpitch);
  55055. this._cosPitch = Math.cos(this._halfpitch);
  55056. this._sinYaw = Math.sin(this._halfyaw);
  55057. this._cosYaw = Math.cos(this._halfyaw);
  55058. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55059. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55060. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55061. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55062. };
  55063. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55064. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55065. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55066. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55067. this._rotMatrix.m[3] = 0;
  55068. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55069. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55070. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55071. this._rotMatrix.m[7] = 0;
  55072. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55073. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55074. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55075. this._rotMatrix.m[11] = 0;
  55076. this._rotMatrix.m[12] = 0;
  55077. this._rotMatrix.m[13] = 0;
  55078. this._rotMatrix.m[14] = 0;
  55079. this._rotMatrix.m[15] = 1.0;
  55080. };
  55081. /**
  55082. * Disposes the SPS.
  55083. */
  55084. SolidParticleSystem.prototype.dispose = function () {
  55085. this.mesh.dispose();
  55086. this.vars = null;
  55087. // drop references to internal big arrays for the GC
  55088. this._positions = null;
  55089. this._indices = null;
  55090. this._normals = null;
  55091. this._uvs = null;
  55092. this._colors = null;
  55093. this._indices32 = null;
  55094. this._positions32 = null;
  55095. this._normals32 = null;
  55096. this._fixedNormal32 = null;
  55097. this._uvs32 = null;
  55098. this._colors32 = null;
  55099. this.pickedParticles = null;
  55100. };
  55101. /**
  55102. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55103. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55104. * @returns the SPS.
  55105. */
  55106. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55107. if (!this._isVisibilityBoxLocked) {
  55108. this.mesh.refreshBoundingInfo();
  55109. }
  55110. return this;
  55111. };
  55112. /**
  55113. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55114. * @param size the size (float) of the visibility box
  55115. * note : this doesn't lock the SPS mesh bounding box.
  55116. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55117. */
  55118. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55119. var vis = size / 2;
  55120. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55121. };
  55122. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55123. /**
  55124. * Gets whether the SPS as always visible or not
  55125. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55126. */
  55127. get: function () {
  55128. return this._alwaysVisible;
  55129. },
  55130. /**
  55131. * Sets the SPS as always visible or not
  55132. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55133. */
  55134. set: function (val) {
  55135. this._alwaysVisible = val;
  55136. this.mesh.alwaysSelectAsActiveMesh = val;
  55137. },
  55138. enumerable: true,
  55139. configurable: true
  55140. });
  55141. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55142. /**
  55143. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55144. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55145. */
  55146. get: function () {
  55147. return this._isVisibilityBoxLocked;
  55148. },
  55149. /**
  55150. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55151. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55152. */
  55153. set: function (val) {
  55154. this._isVisibilityBoxLocked = val;
  55155. var boundingInfo = this.mesh.getBoundingInfo();
  55156. boundingInfo.isLocked = val;
  55157. },
  55158. enumerable: true,
  55159. configurable: true
  55160. });
  55161. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55162. /**
  55163. * Gets if `setParticles()` computes the particle rotations or not.
  55164. * Default value : true. The SPS is faster when it's set to false.
  55165. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55166. */
  55167. get: function () {
  55168. return this._computeParticleRotation;
  55169. },
  55170. /**
  55171. * Tells to `setParticles()` to compute the particle rotations or not.
  55172. * Default value : true. The SPS is faster when it's set to false.
  55173. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55174. */
  55175. set: function (val) {
  55176. this._computeParticleRotation = val;
  55177. },
  55178. enumerable: true,
  55179. configurable: true
  55180. });
  55181. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55182. /**
  55183. * Gets if `setParticles()` computes the particle colors or not.
  55184. * Default value : true. The SPS is faster when it's set to false.
  55185. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55186. */
  55187. get: function () {
  55188. return this._computeParticleColor;
  55189. },
  55190. /**
  55191. * Tells to `setParticles()` to compute the particle colors or not.
  55192. * Default value : true. The SPS is faster when it's set to false.
  55193. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55194. */
  55195. set: function (val) {
  55196. this._computeParticleColor = val;
  55197. },
  55198. enumerable: true,
  55199. configurable: true
  55200. });
  55201. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55202. /**
  55203. * Gets if `setParticles()` computes the particle textures or not.
  55204. * Default value : true. The SPS is faster when it's set to false.
  55205. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55206. */
  55207. get: function () {
  55208. return this._computeParticleTexture;
  55209. },
  55210. set: function (val) {
  55211. this._computeParticleTexture = val;
  55212. },
  55213. enumerable: true,
  55214. configurable: true
  55215. });
  55216. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55217. /**
  55218. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55219. * Default value : false. The SPS is faster when it's set to false.
  55220. * Note : the particle custom vertex positions aren't stored values.
  55221. */
  55222. get: function () {
  55223. return this._computeParticleVertex;
  55224. },
  55225. /**
  55226. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55227. * Default value : false. The SPS is faster when it's set to false.
  55228. * Note : the particle custom vertex positions aren't stored values.
  55229. */
  55230. set: function (val) {
  55231. this._computeParticleVertex = val;
  55232. },
  55233. enumerable: true,
  55234. configurable: true
  55235. });
  55236. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55237. /**
  55238. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55239. */
  55240. get: function () {
  55241. return this._computeBoundingBox;
  55242. },
  55243. /**
  55244. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55245. */
  55246. set: function (val) {
  55247. this._computeBoundingBox = val;
  55248. },
  55249. enumerable: true,
  55250. configurable: true
  55251. });
  55252. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55253. /**
  55254. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55255. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55256. * Default : `true`
  55257. */
  55258. get: function () {
  55259. return this._depthSortParticles;
  55260. },
  55261. /**
  55262. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55263. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55264. * Default : `true`
  55265. */
  55266. set: function (val) {
  55267. this._depthSortParticles = val;
  55268. },
  55269. enumerable: true,
  55270. configurable: true
  55271. });
  55272. // =======================================================================
  55273. // Particle behavior logic
  55274. // these following methods may be overwritten by the user to fit his needs
  55275. /**
  55276. * This function does nothing. It may be overwritten to set all the particle first values.
  55277. * The SPS doesn't call this function, you may have to call it by your own.
  55278. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55279. */
  55280. SolidParticleSystem.prototype.initParticles = function () {
  55281. };
  55282. /**
  55283. * This function does nothing. It may be overwritten to recycle a particle.
  55284. * The SPS doesn't call this function, you may have to call it by your own.
  55285. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55286. * @param particle The particle to recycle
  55287. * @returns the recycled particle
  55288. */
  55289. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55290. return particle;
  55291. };
  55292. /**
  55293. * Updates a particle : this function should be overwritten by the user.
  55294. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55295. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55296. * @example : just set a particle position or velocity and recycle conditions
  55297. * @param particle The particle to update
  55298. * @returns the updated particle
  55299. */
  55300. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55301. return particle;
  55302. };
  55303. /**
  55304. * Updates a vertex of a particle : it can be overwritten by the user.
  55305. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55306. * @param particle the current particle
  55307. * @param vertex the current index of the current particle
  55308. * @param pt the index of the current vertex in the particle shape
  55309. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55310. * @example : just set a vertex particle position
  55311. * @returns the updated vertex
  55312. */
  55313. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55314. return vertex;
  55315. };
  55316. /**
  55317. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55318. * This does nothing and may be overwritten by the user.
  55319. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55320. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55321. * @param update the boolean update value actually passed to setParticles()
  55322. */
  55323. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55324. };
  55325. /**
  55326. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55327. * This will be passed three parameters.
  55328. * This does nothing and may be overwritten by the user.
  55329. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55330. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55331. * @param update the boolean update value actually passed to setParticles()
  55332. */
  55333. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55334. };
  55335. return SolidParticleSystem;
  55336. }());
  55337. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55338. })(BABYLON || (BABYLON = {}));
  55339. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55340. "use strict";
  55341. var BABYLON;
  55342. (function (BABYLON) {
  55343. var ShaderMaterial = /** @class */ (function (_super) {
  55344. __extends(ShaderMaterial, _super);
  55345. function ShaderMaterial(name, scene, shaderPath, options) {
  55346. var _this = _super.call(this, name, scene) || this;
  55347. _this._textures = {};
  55348. _this._textureArrays = {};
  55349. _this._floats = {};
  55350. _this._ints = {};
  55351. _this._floatsArrays = {};
  55352. _this._colors3 = {};
  55353. _this._colors3Arrays = {};
  55354. _this._colors4 = {};
  55355. _this._vectors2 = {};
  55356. _this._vectors3 = {};
  55357. _this._vectors4 = {};
  55358. _this._matrices = {};
  55359. _this._matrices3x3 = {};
  55360. _this._matrices2x2 = {};
  55361. _this._vectors2Arrays = {};
  55362. _this._vectors3Arrays = {};
  55363. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55364. _this._shaderPath = shaderPath;
  55365. options.needAlphaBlending = options.needAlphaBlending || false;
  55366. options.needAlphaTesting = options.needAlphaTesting || false;
  55367. options.attributes = options.attributes || ["position", "normal", "uv"];
  55368. options.uniforms = options.uniforms || ["worldViewProjection"];
  55369. options.uniformBuffers = options.uniformBuffers || [];
  55370. options.samplers = options.samplers || [];
  55371. options.defines = options.defines || [];
  55372. _this._options = options;
  55373. return _this;
  55374. }
  55375. ShaderMaterial.prototype.getClassName = function () {
  55376. return "ShaderMaterial";
  55377. };
  55378. ShaderMaterial.prototype.needAlphaBlending = function () {
  55379. return this._options.needAlphaBlending;
  55380. };
  55381. ShaderMaterial.prototype.needAlphaTesting = function () {
  55382. return this._options.needAlphaTesting;
  55383. };
  55384. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55385. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55386. this._options.uniforms.push(uniformName);
  55387. }
  55388. };
  55389. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55390. if (this._options.samplers.indexOf(name) === -1) {
  55391. this._options.samplers.push(name);
  55392. }
  55393. this._textures[name] = texture;
  55394. return this;
  55395. };
  55396. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55397. if (this._options.samplers.indexOf(name) === -1) {
  55398. this._options.samplers.push(name);
  55399. }
  55400. this._checkUniform(name);
  55401. this._textureArrays[name] = textures;
  55402. return this;
  55403. };
  55404. ShaderMaterial.prototype.setFloat = function (name, value) {
  55405. this._checkUniform(name);
  55406. this._floats[name] = value;
  55407. return this;
  55408. };
  55409. ShaderMaterial.prototype.setInt = function (name, value) {
  55410. this._checkUniform(name);
  55411. this._ints[name] = value;
  55412. return this;
  55413. };
  55414. ShaderMaterial.prototype.setFloats = function (name, value) {
  55415. this._checkUniform(name);
  55416. this._floatsArrays[name] = value;
  55417. return this;
  55418. };
  55419. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55420. this._checkUniform(name);
  55421. this._colors3[name] = value;
  55422. return this;
  55423. };
  55424. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55425. this._checkUniform(name);
  55426. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55427. color.toArray(arr, arr.length);
  55428. return arr;
  55429. }, []);
  55430. return this;
  55431. };
  55432. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55433. this._checkUniform(name);
  55434. this._colors4[name] = value;
  55435. return this;
  55436. };
  55437. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55438. this._checkUniform(name);
  55439. this._vectors2[name] = value;
  55440. return this;
  55441. };
  55442. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55443. this._checkUniform(name);
  55444. this._vectors3[name] = value;
  55445. return this;
  55446. };
  55447. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55448. this._checkUniform(name);
  55449. this._vectors4[name] = value;
  55450. return this;
  55451. };
  55452. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55453. this._checkUniform(name);
  55454. this._matrices[name] = value;
  55455. return this;
  55456. };
  55457. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55458. this._checkUniform(name);
  55459. this._matrices3x3[name] = value;
  55460. return this;
  55461. };
  55462. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55463. this._checkUniform(name);
  55464. this._matrices2x2[name] = value;
  55465. return this;
  55466. };
  55467. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55468. this._checkUniform(name);
  55469. this._vectors2Arrays[name] = value;
  55470. return this;
  55471. };
  55472. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55473. this._checkUniform(name);
  55474. this._vectors3Arrays[name] = value;
  55475. return this;
  55476. };
  55477. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55478. if (!mesh) {
  55479. return true;
  55480. }
  55481. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55482. return false;
  55483. }
  55484. return false;
  55485. };
  55486. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55487. var scene = this.getScene();
  55488. var engine = scene.getEngine();
  55489. if (!this.checkReadyOnEveryCall) {
  55490. if (this._renderId === scene.getRenderId()) {
  55491. if (this._checkCache(scene, mesh, useInstances)) {
  55492. return true;
  55493. }
  55494. }
  55495. }
  55496. // Instances
  55497. var defines = [];
  55498. var attribs = [];
  55499. var fallbacks = new BABYLON.EffectFallbacks();
  55500. if (useInstances) {
  55501. defines.push("#define INSTANCES");
  55502. }
  55503. for (var index = 0; index < this._options.defines.length; index++) {
  55504. defines.push(this._options.defines[index]);
  55505. }
  55506. for (var index = 0; index < this._options.attributes.length; index++) {
  55507. attribs.push(this._options.attributes[index]);
  55508. }
  55509. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55510. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55511. defines.push("#define VERTEXCOLOR");
  55512. }
  55513. // Bones
  55514. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55515. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55516. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55517. if (mesh.numBoneInfluencers > 4) {
  55518. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55519. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55520. }
  55521. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55522. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55523. fallbacks.addCPUSkinningFallback(0, mesh);
  55524. if (this._options.uniforms.indexOf("mBones") === -1) {
  55525. this._options.uniforms.push("mBones");
  55526. }
  55527. }
  55528. else {
  55529. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55530. }
  55531. // Textures
  55532. for (var name in this._textures) {
  55533. if (!this._textures[name].isReady()) {
  55534. return false;
  55535. }
  55536. }
  55537. // Alpha test
  55538. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55539. defines.push("#define ALPHATEST");
  55540. }
  55541. var previousEffect = this._effect;
  55542. var join = defines.join("\n");
  55543. this._effect = engine.createEffect(this._shaderPath, {
  55544. attributes: attribs,
  55545. uniformsNames: this._options.uniforms,
  55546. uniformBuffersNames: this._options.uniformBuffers,
  55547. samplers: this._options.samplers,
  55548. defines: join,
  55549. fallbacks: fallbacks,
  55550. onCompiled: this.onCompiled,
  55551. onError: this.onError
  55552. }, engine);
  55553. if (!this._effect.isReady()) {
  55554. return false;
  55555. }
  55556. if (previousEffect !== this._effect) {
  55557. scene.resetCachedMaterial();
  55558. }
  55559. this._renderId = scene.getRenderId();
  55560. return true;
  55561. };
  55562. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55563. var scene = this.getScene();
  55564. if (!this._effect) {
  55565. return;
  55566. }
  55567. if (this._options.uniforms.indexOf("world") !== -1) {
  55568. this._effect.setMatrix("world", world);
  55569. }
  55570. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55571. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55572. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55573. }
  55574. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55575. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55576. }
  55577. };
  55578. ShaderMaterial.prototype.bind = function (world, mesh) {
  55579. // Std values
  55580. this.bindOnlyWorldMatrix(world);
  55581. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55582. if (this._options.uniforms.indexOf("view") !== -1) {
  55583. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55584. }
  55585. if (this._options.uniforms.indexOf("projection") !== -1) {
  55586. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55587. }
  55588. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55589. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55590. }
  55591. // Bones
  55592. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55593. var name;
  55594. // Texture
  55595. for (name in this._textures) {
  55596. this._effect.setTexture(name, this._textures[name]);
  55597. }
  55598. // Texture arrays
  55599. for (name in this._textureArrays) {
  55600. this._effect.setTextureArray(name, this._textureArrays[name]);
  55601. }
  55602. // Int
  55603. for (name in this._ints) {
  55604. this._effect.setInt(name, this._ints[name]);
  55605. }
  55606. // Float
  55607. for (name in this._floats) {
  55608. this._effect.setFloat(name, this._floats[name]);
  55609. }
  55610. // Floats
  55611. for (name in this._floatsArrays) {
  55612. this._effect.setArray(name, this._floatsArrays[name]);
  55613. }
  55614. // Color3
  55615. for (name in this._colors3) {
  55616. this._effect.setColor3(name, this._colors3[name]);
  55617. }
  55618. for (name in this._colors3Arrays) {
  55619. this._effect.setArray3(name, this._colors3Arrays[name]);
  55620. }
  55621. // Color4
  55622. for (name in this._colors4) {
  55623. var color = this._colors4[name];
  55624. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55625. }
  55626. // Vector2
  55627. for (name in this._vectors2) {
  55628. this._effect.setVector2(name, this._vectors2[name]);
  55629. }
  55630. // Vector3
  55631. for (name in this._vectors3) {
  55632. this._effect.setVector3(name, this._vectors3[name]);
  55633. }
  55634. // Vector4
  55635. for (name in this._vectors4) {
  55636. this._effect.setVector4(name, this._vectors4[name]);
  55637. }
  55638. // Matrix
  55639. for (name in this._matrices) {
  55640. this._effect.setMatrix(name, this._matrices[name]);
  55641. }
  55642. // Matrix 3x3
  55643. for (name in this._matrices3x3) {
  55644. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55645. }
  55646. // Matrix 2x2
  55647. for (name in this._matrices2x2) {
  55648. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55649. }
  55650. // Vector2Array
  55651. for (name in this._vectors2Arrays) {
  55652. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55653. }
  55654. // Vector3Array
  55655. for (name in this._vectors3Arrays) {
  55656. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55657. }
  55658. }
  55659. this._afterBind(mesh);
  55660. };
  55661. ShaderMaterial.prototype.getActiveTextures = function () {
  55662. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55663. for (var name in this._textures) {
  55664. activeTextures.push(this._textures[name]);
  55665. }
  55666. for (var name in this._textureArrays) {
  55667. var array = this._textureArrays[name];
  55668. for (var index = 0; index < array.length; index++) {
  55669. activeTextures.push(array[index]);
  55670. }
  55671. }
  55672. return activeTextures;
  55673. };
  55674. ShaderMaterial.prototype.hasTexture = function (texture) {
  55675. if (_super.prototype.hasTexture.call(this, texture)) {
  55676. return true;
  55677. }
  55678. for (var name in this._textures) {
  55679. if (this._textures[name] === texture) {
  55680. return true;
  55681. }
  55682. }
  55683. for (var name in this._textureArrays) {
  55684. var array = this._textureArrays[name];
  55685. for (var index = 0; index < array.length; index++) {
  55686. if (array[index] === texture) {
  55687. return true;
  55688. }
  55689. }
  55690. }
  55691. return false;
  55692. };
  55693. ShaderMaterial.prototype.clone = function (name) {
  55694. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55695. return newShaderMaterial;
  55696. };
  55697. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55698. if (forceDisposeTextures) {
  55699. var name;
  55700. for (name in this._textures) {
  55701. this._textures[name].dispose();
  55702. }
  55703. for (name in this._textureArrays) {
  55704. var array = this._textureArrays[name];
  55705. for (var index = 0; index < array.length; index++) {
  55706. array[index].dispose();
  55707. }
  55708. }
  55709. }
  55710. this._textures = {};
  55711. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55712. };
  55713. ShaderMaterial.prototype.serialize = function () {
  55714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55715. serializationObject.customType = "BABYLON.ShaderMaterial";
  55716. serializationObject.options = this._options;
  55717. serializationObject.shaderPath = this._shaderPath;
  55718. var name;
  55719. // Texture
  55720. serializationObject.textures = {};
  55721. for (name in this._textures) {
  55722. serializationObject.textures[name] = this._textures[name].serialize();
  55723. }
  55724. // Texture arrays
  55725. serializationObject.textureArrays = {};
  55726. for (name in this._textureArrays) {
  55727. serializationObject.textureArrays[name] = [];
  55728. var array = this._textureArrays[name];
  55729. for (var index = 0; index < array.length; index++) {
  55730. serializationObject.textureArrays[name].push(array[index].serialize());
  55731. }
  55732. }
  55733. // Float
  55734. serializationObject.floats = {};
  55735. for (name in this._floats) {
  55736. serializationObject.floats[name] = this._floats[name];
  55737. }
  55738. // Float s
  55739. serializationObject.FloatArrays = {};
  55740. for (name in this._floatsArrays) {
  55741. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55742. }
  55743. // Color3
  55744. serializationObject.colors3 = {};
  55745. for (name in this._colors3) {
  55746. serializationObject.colors3[name] = this._colors3[name].asArray();
  55747. }
  55748. // Color3 array
  55749. serializationObject.colors3Arrays = {};
  55750. for (name in this._colors3Arrays) {
  55751. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55752. }
  55753. // Color4
  55754. serializationObject.colors4 = {};
  55755. for (name in this._colors4) {
  55756. serializationObject.colors4[name] = this._colors4[name].asArray();
  55757. }
  55758. // Vector2
  55759. serializationObject.vectors2 = {};
  55760. for (name in this._vectors2) {
  55761. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55762. }
  55763. // Vector3
  55764. serializationObject.vectors3 = {};
  55765. for (name in this._vectors3) {
  55766. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55767. }
  55768. // Vector4
  55769. serializationObject.vectors4 = {};
  55770. for (name in this._vectors4) {
  55771. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55772. }
  55773. // Matrix
  55774. serializationObject.matrices = {};
  55775. for (name in this._matrices) {
  55776. serializationObject.matrices[name] = this._matrices[name].asArray();
  55777. }
  55778. // Matrix 3x3
  55779. serializationObject.matrices3x3 = {};
  55780. for (name in this._matrices3x3) {
  55781. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55782. }
  55783. // Matrix 2x2
  55784. serializationObject.matrices2x2 = {};
  55785. for (name in this._matrices2x2) {
  55786. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55787. }
  55788. // Vector2Array
  55789. serializationObject.vectors2Arrays = {};
  55790. for (name in this._vectors2Arrays) {
  55791. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55792. }
  55793. // Vector3Array
  55794. serializationObject.vectors3Arrays = {};
  55795. for (name in this._vectors3Arrays) {
  55796. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55797. }
  55798. return serializationObject;
  55799. };
  55800. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55801. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55802. var name;
  55803. // Texture
  55804. for (name in source.textures) {
  55805. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55806. }
  55807. // Texture arrays
  55808. for (name in source.textureArrays) {
  55809. var array = source.textureArrays[name];
  55810. var textureArray = new Array();
  55811. for (var index = 0; index < array.length; index++) {
  55812. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55813. }
  55814. material.setTextureArray(name, textureArray);
  55815. }
  55816. // Float
  55817. for (name in source.floats) {
  55818. material.setFloat(name, source.floats[name]);
  55819. }
  55820. // Float s
  55821. for (name in source.floatsArrays) {
  55822. material.setFloats(name, source.floatsArrays[name]);
  55823. }
  55824. // Color3
  55825. for (name in source.colors3) {
  55826. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55827. }
  55828. // Color3 arrays
  55829. for (name in source.colors3Arrays) {
  55830. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55831. if (i % 3 === 0) {
  55832. arr.push([num]);
  55833. }
  55834. else {
  55835. arr[arr.length - 1].push(num);
  55836. }
  55837. return arr;
  55838. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55839. material.setColor3Array(name, colors);
  55840. }
  55841. // Color4
  55842. for (name in source.colors4) {
  55843. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55844. }
  55845. // Vector2
  55846. for (name in source.vectors2) {
  55847. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55848. }
  55849. // Vector3
  55850. for (name in source.vectors3) {
  55851. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55852. }
  55853. // Vector4
  55854. for (name in source.vectors4) {
  55855. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55856. }
  55857. // Matrix
  55858. for (name in source.matrices) {
  55859. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55860. }
  55861. // Matrix 3x3
  55862. for (name in source.matrices3x3) {
  55863. material.setMatrix3x3(name, source.matrices3x3[name]);
  55864. }
  55865. // Matrix 2x2
  55866. for (name in source.matrices2x2) {
  55867. material.setMatrix2x2(name, source.matrices2x2[name]);
  55868. }
  55869. // Vector2Array
  55870. for (name in source.vectors2Arrays) {
  55871. material.setArray2(name, source.vectors2Arrays[name]);
  55872. }
  55873. // Vector3Array
  55874. for (name in source.vectors3Arrays) {
  55875. material.setArray3(name, source.vectors3Arrays[name]);
  55876. }
  55877. return material;
  55878. };
  55879. return ShaderMaterial;
  55880. }(BABYLON.Material));
  55881. BABYLON.ShaderMaterial = ShaderMaterial;
  55882. })(BABYLON || (BABYLON = {}));
  55883. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55884. "use strict";
  55885. var BABYLON;
  55886. (function (BABYLON) {
  55887. var GroundMesh = /** @class */ (function (_super) {
  55888. __extends(GroundMesh, _super);
  55889. function GroundMesh(name, scene) {
  55890. var _this = _super.call(this, name, scene) || this;
  55891. _this.generateOctree = false;
  55892. return _this;
  55893. }
  55894. GroundMesh.prototype.getClassName = function () {
  55895. return "GroundMesh";
  55896. };
  55897. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55898. get: function () {
  55899. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55900. },
  55901. enumerable: true,
  55902. configurable: true
  55903. });
  55904. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55905. get: function () {
  55906. return this._subdivisionsX;
  55907. },
  55908. enumerable: true,
  55909. configurable: true
  55910. });
  55911. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55912. get: function () {
  55913. return this._subdivisionsY;
  55914. },
  55915. enumerable: true,
  55916. configurable: true
  55917. });
  55918. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55919. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55920. this._subdivisionsX = chunksCount;
  55921. this._subdivisionsY = chunksCount;
  55922. this.subdivide(chunksCount);
  55923. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55924. };
  55925. /**
  55926. * Returns a height (y) value in the Worl system :
  55927. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55928. * Returns the ground y position if (x, z) are outside the ground surface.
  55929. */
  55930. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55931. var world = this.getWorldMatrix();
  55932. var invMat = BABYLON.Tmp.Matrix[5];
  55933. world.invertToRef(invMat);
  55934. var tmpVect = BABYLON.Tmp.Vector3[8];
  55935. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55936. x = tmpVect.x;
  55937. z = tmpVect.z;
  55938. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55939. return this.position.y;
  55940. }
  55941. if (!this._heightQuads || this._heightQuads.length == 0) {
  55942. this._initHeightQuads();
  55943. this._computeHeightQuads();
  55944. }
  55945. var facet = this._getFacetAt(x, z);
  55946. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55947. // return y in the World system
  55948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55949. return tmpVect.y;
  55950. };
  55951. /**
  55952. * Returns a normalized vector (Vector3) orthogonal to the ground
  55953. * at the ground coordinates (x, z) expressed in the World system.
  55954. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55955. */
  55956. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55957. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55958. this.getNormalAtCoordinatesToRef(x, z, normal);
  55959. return normal;
  55960. };
  55961. /**
  55962. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55963. * at the ground coordinates (x, z) expressed in the World system.
  55964. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55965. * Returns the GroundMesh.
  55966. */
  55967. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55968. var world = this.getWorldMatrix();
  55969. var tmpMat = BABYLON.Tmp.Matrix[5];
  55970. world.invertToRef(tmpMat);
  55971. var tmpVect = BABYLON.Tmp.Vector3[8];
  55972. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55973. x = tmpVect.x;
  55974. z = tmpVect.z;
  55975. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55976. return this;
  55977. }
  55978. if (!this._heightQuads || this._heightQuads.length == 0) {
  55979. this._initHeightQuads();
  55980. this._computeHeightQuads();
  55981. }
  55982. var facet = this._getFacetAt(x, z);
  55983. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55984. return this;
  55985. };
  55986. /**
  55987. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55988. * if the ground has been updated.
  55989. * This can be used in the render loop.
  55990. * Returns the GroundMesh.
  55991. */
  55992. GroundMesh.prototype.updateCoordinateHeights = function () {
  55993. if (!this._heightQuads || this._heightQuads.length == 0) {
  55994. this._initHeightQuads();
  55995. }
  55996. this._computeHeightQuads();
  55997. return this;
  55998. };
  55999. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  56000. GroundMesh.prototype._getFacetAt = function (x, z) {
  56001. // retrieve col and row from x, z coordinates in the ground local system
  56002. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  56003. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  56004. var quad = this._heightQuads[row * this._subdivisionsX + col];
  56005. var facet;
  56006. if (z < quad.slope.x * x + quad.slope.y) {
  56007. facet = quad.facet1;
  56008. }
  56009. else {
  56010. facet = quad.facet2;
  56011. }
  56012. return facet;
  56013. };
  56014. // Creates and populates the heightMap array with "facet" elements :
  56015. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  56016. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56017. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56018. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56019. // Returns the GroundMesh.
  56020. GroundMesh.prototype._initHeightQuads = function () {
  56021. var subdivisionsX = this._subdivisionsX;
  56022. var subdivisionsY = this._subdivisionsY;
  56023. this._heightQuads = new Array();
  56024. for (var row = 0; row < subdivisionsY; row++) {
  56025. for (var col = 0; col < subdivisionsX; col++) {
  56026. 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) };
  56027. this._heightQuads[row * subdivisionsX + col] = quad;
  56028. }
  56029. }
  56030. return this;
  56031. };
  56032. // Compute each quad element values and update the the heightMap array :
  56033. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56034. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56035. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56036. // Returns the GroundMesh.
  56037. GroundMesh.prototype._computeHeightQuads = function () {
  56038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56039. if (!positions) {
  56040. return this;
  56041. }
  56042. var v1 = BABYLON.Tmp.Vector3[3];
  56043. var v2 = BABYLON.Tmp.Vector3[2];
  56044. var v3 = BABYLON.Tmp.Vector3[1];
  56045. var v4 = BABYLON.Tmp.Vector3[0];
  56046. var v1v2 = BABYLON.Tmp.Vector3[4];
  56047. var v1v3 = BABYLON.Tmp.Vector3[5];
  56048. var v1v4 = BABYLON.Tmp.Vector3[6];
  56049. var norm1 = BABYLON.Tmp.Vector3[7];
  56050. var norm2 = BABYLON.Tmp.Vector3[8];
  56051. var i = 0;
  56052. var j = 0;
  56053. var k = 0;
  56054. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56055. var h = 0;
  56056. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56057. var d2 = 0;
  56058. var subdivisionsX = this._subdivisionsX;
  56059. var subdivisionsY = this._subdivisionsY;
  56060. for (var row = 0; row < subdivisionsY; row++) {
  56061. for (var col = 0; col < subdivisionsX; col++) {
  56062. i = col * 3;
  56063. j = row * (subdivisionsX + 1) * 3;
  56064. k = (row + 1) * (subdivisionsX + 1) * 3;
  56065. v1.x = positions[j + i];
  56066. v1.y = positions[j + i + 1];
  56067. v1.z = positions[j + i + 2];
  56068. v2.x = positions[j + i + 3];
  56069. v2.y = positions[j + i + 4];
  56070. v2.z = positions[j + i + 5];
  56071. v3.x = positions[k + i];
  56072. v3.y = positions[k + i + 1];
  56073. v3.z = positions[k + i + 2];
  56074. v4.x = positions[k + i + 3];
  56075. v4.y = positions[k + i + 4];
  56076. v4.z = positions[k + i + 5];
  56077. // 2D slope V1V4
  56078. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56079. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56080. // facet equations :
  56081. // we compute each facet normal vector
  56082. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56083. // we compute the value d by applying the equation to v1 which belongs to the plane
  56084. // then we store the facet equation in a Vector4
  56085. v2.subtractToRef(v1, v1v2);
  56086. v3.subtractToRef(v1, v1v3);
  56087. v4.subtractToRef(v1, v1v4);
  56088. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56089. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56090. norm1.normalize();
  56091. norm2.normalize();
  56092. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56093. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56094. var quad = this._heightQuads[row * subdivisionsX + col];
  56095. quad.slope.copyFromFloats(cd, h);
  56096. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56097. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56098. }
  56099. }
  56100. return this;
  56101. };
  56102. GroundMesh.prototype.serialize = function (serializationObject) {
  56103. _super.prototype.serialize.call(this, serializationObject);
  56104. serializationObject.subdivisionsX = this._subdivisionsX;
  56105. serializationObject.subdivisionsY = this._subdivisionsY;
  56106. serializationObject.minX = this._minX;
  56107. serializationObject.maxX = this._maxX;
  56108. serializationObject.minZ = this._minZ;
  56109. serializationObject.maxZ = this._maxZ;
  56110. serializationObject.width = this._width;
  56111. serializationObject.height = this._height;
  56112. };
  56113. GroundMesh.Parse = function (parsedMesh, scene) {
  56114. var result = new GroundMesh(parsedMesh.name, scene);
  56115. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56116. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56117. result._minX = parsedMesh.minX;
  56118. result._maxX = parsedMesh.maxX;
  56119. result._minZ = parsedMesh.minZ;
  56120. result._maxZ = parsedMesh.maxZ;
  56121. result._width = parsedMesh.width;
  56122. result._height = parsedMesh.height;
  56123. return result;
  56124. };
  56125. return GroundMesh;
  56126. }(BABYLON.Mesh));
  56127. BABYLON.GroundMesh = GroundMesh;
  56128. })(BABYLON || (BABYLON = {}));
  56129. //# sourceMappingURL=babylon.groundMesh.js.map
  56130. "use strict";
  56131. var BABYLON;
  56132. (function (BABYLON) {
  56133. /**
  56134. * Creates an instance based on a source mesh.
  56135. */
  56136. var InstancedMesh = /** @class */ (function (_super) {
  56137. __extends(InstancedMesh, _super);
  56138. function InstancedMesh(name, source) {
  56139. var _this = _super.call(this, name, source.getScene()) || this;
  56140. source.instances.push(_this);
  56141. _this._sourceMesh = source;
  56142. _this.position.copyFrom(source.position);
  56143. _this.rotation.copyFrom(source.rotation);
  56144. _this.scaling.copyFrom(source.scaling);
  56145. if (source.rotationQuaternion) {
  56146. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56147. }
  56148. _this.infiniteDistance = source.infiniteDistance;
  56149. _this.setPivotMatrix(source.getPivotMatrix());
  56150. _this.refreshBoundingInfo();
  56151. _this._syncSubMeshes();
  56152. return _this;
  56153. }
  56154. /**
  56155. * Returns the string "InstancedMesh".
  56156. */
  56157. InstancedMesh.prototype.getClassName = function () {
  56158. return "InstancedMesh";
  56159. };
  56160. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56161. // Methods
  56162. get: function () {
  56163. return this._sourceMesh.receiveShadows;
  56164. },
  56165. enumerable: true,
  56166. configurable: true
  56167. });
  56168. Object.defineProperty(InstancedMesh.prototype, "material", {
  56169. get: function () {
  56170. return this._sourceMesh.material;
  56171. },
  56172. enumerable: true,
  56173. configurable: true
  56174. });
  56175. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56176. get: function () {
  56177. return this._sourceMesh.visibility;
  56178. },
  56179. enumerable: true,
  56180. configurable: true
  56181. });
  56182. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56183. get: function () {
  56184. return this._sourceMesh.skeleton;
  56185. },
  56186. enumerable: true,
  56187. configurable: true
  56188. });
  56189. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56190. get: function () {
  56191. return this._sourceMesh.renderingGroupId;
  56192. },
  56193. set: function (value) {
  56194. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56195. return;
  56196. }
  56197. //no-op with warning
  56198. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56199. },
  56200. enumerable: true,
  56201. configurable: true
  56202. });
  56203. /**
  56204. * Returns the total number of vertices (integer).
  56205. */
  56206. InstancedMesh.prototype.getTotalVertices = function () {
  56207. return this._sourceMesh.getTotalVertices();
  56208. };
  56209. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56210. get: function () {
  56211. return this._sourceMesh;
  56212. },
  56213. enumerable: true,
  56214. configurable: true
  56215. });
  56216. /**
  56217. * Is this node ready to be used/rendered
  56218. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56219. * @return {boolean} is it ready
  56220. */
  56221. InstancedMesh.prototype.isReady = function (completeCheck) {
  56222. if (completeCheck === void 0) { completeCheck = false; }
  56223. return this._sourceMesh.isReady(completeCheck, true);
  56224. };
  56225. /**
  56226. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56227. */
  56228. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56229. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56230. };
  56231. /**
  56232. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56233. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56234. * The `data` are either a numeric array either a Float32Array.
  56235. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56236. * 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).
  56237. * Note that a new underlying VertexBuffer object is created each call.
  56238. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56239. *
  56240. * Possible `kind` values :
  56241. * - BABYLON.VertexBuffer.PositionKind
  56242. * - BABYLON.VertexBuffer.UVKind
  56243. * - BABYLON.VertexBuffer.UV2Kind
  56244. * - BABYLON.VertexBuffer.UV3Kind
  56245. * - BABYLON.VertexBuffer.UV4Kind
  56246. * - BABYLON.VertexBuffer.UV5Kind
  56247. * - BABYLON.VertexBuffer.UV6Kind
  56248. * - BABYLON.VertexBuffer.ColorKind
  56249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56253. *
  56254. * Returns the Mesh.
  56255. */
  56256. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56257. if (this.sourceMesh) {
  56258. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56259. }
  56260. return this.sourceMesh;
  56261. };
  56262. /**
  56263. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56264. * If the mesh has no geometry, it is simply returned as it is.
  56265. * The `data` are either a numeric array either a Float32Array.
  56266. * No new underlying VertexBuffer object is created.
  56267. * 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.
  56268. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56269. *
  56270. * Possible `kind` values :
  56271. * - BABYLON.VertexBuffer.PositionKind
  56272. * - BABYLON.VertexBuffer.UVKind
  56273. * - BABYLON.VertexBuffer.UV2Kind
  56274. * - BABYLON.VertexBuffer.UV3Kind
  56275. * - BABYLON.VertexBuffer.UV4Kind
  56276. * - BABYLON.VertexBuffer.UV5Kind
  56277. * - BABYLON.VertexBuffer.UV6Kind
  56278. * - BABYLON.VertexBuffer.ColorKind
  56279. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56280. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56281. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56282. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56283. *
  56284. * Returns the Mesh.
  56285. */
  56286. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56287. if (this.sourceMesh) {
  56288. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56289. }
  56290. return this.sourceMesh;
  56291. };
  56292. /**
  56293. * Sets the mesh indices.
  56294. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56295. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56296. * This method creates a new index buffer each call.
  56297. * Returns the Mesh.
  56298. */
  56299. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56300. if (totalVertices === void 0) { totalVertices = null; }
  56301. if (this.sourceMesh) {
  56302. this.sourceMesh.setIndices(indices, totalVertices);
  56303. }
  56304. return this.sourceMesh;
  56305. };
  56306. /**
  56307. * Boolean : True if the mesh owns the requested kind of data.
  56308. */
  56309. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56310. return this._sourceMesh.isVerticesDataPresent(kind);
  56311. };
  56312. /**
  56313. * Returns an array of indices (IndicesArray).
  56314. */
  56315. InstancedMesh.prototype.getIndices = function () {
  56316. return this._sourceMesh.getIndices();
  56317. };
  56318. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56319. get: function () {
  56320. return this._sourceMesh._positions;
  56321. },
  56322. enumerable: true,
  56323. configurable: true
  56324. });
  56325. /**
  56326. * Sets a new updated BoundingInfo to the mesh.
  56327. * Returns the mesh.
  56328. */
  56329. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56330. var meshBB = this._sourceMesh.getBoundingInfo();
  56331. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56332. this._updateBoundingInfo();
  56333. return this;
  56334. };
  56335. InstancedMesh.prototype._preActivate = function () {
  56336. if (this._currentLOD) {
  56337. this._currentLOD._preActivate();
  56338. }
  56339. return this;
  56340. };
  56341. InstancedMesh.prototype._activate = function (renderId) {
  56342. if (this._currentLOD) {
  56343. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56344. }
  56345. return this;
  56346. };
  56347. /**
  56348. * Returns the current associated LOD AbstractMesh.
  56349. */
  56350. InstancedMesh.prototype.getLOD = function (camera) {
  56351. if (!camera) {
  56352. return this;
  56353. }
  56354. var boundingInfo = this.getBoundingInfo();
  56355. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56356. if (this._currentLOD === this.sourceMesh) {
  56357. return this;
  56358. }
  56359. return this._currentLOD;
  56360. };
  56361. InstancedMesh.prototype._syncSubMeshes = function () {
  56362. this.releaseSubMeshes();
  56363. if (this._sourceMesh.subMeshes) {
  56364. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56365. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56366. }
  56367. }
  56368. return this;
  56369. };
  56370. InstancedMesh.prototype._generatePointsArray = function () {
  56371. return this._sourceMesh._generatePointsArray();
  56372. };
  56373. /**
  56374. * Creates a new InstancedMesh from the current mesh.
  56375. * - name (string) : the cloned mesh name
  56376. * - newParent (optional Node) : the optional Node to parent the clone to.
  56377. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56378. *
  56379. * Returns the clone.
  56380. */
  56381. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56382. var result = this._sourceMesh.createInstance(name);
  56383. // Deep copy
  56384. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56385. // Bounding info
  56386. this.refreshBoundingInfo();
  56387. // Parent
  56388. if (newParent) {
  56389. result.parent = newParent;
  56390. }
  56391. if (!doNotCloneChildren) {
  56392. // Children
  56393. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56394. var mesh = this.getScene().meshes[index];
  56395. if (mesh.parent === this) {
  56396. mesh.clone(mesh.name, result);
  56397. }
  56398. }
  56399. }
  56400. result.computeWorldMatrix(true);
  56401. return result;
  56402. };
  56403. /**
  56404. * Disposes the InstancedMesh.
  56405. * Returns nothing.
  56406. */
  56407. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56408. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56409. // Remove from mesh
  56410. var index = this._sourceMesh.instances.indexOf(this);
  56411. this._sourceMesh.instances.splice(index, 1);
  56412. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56413. };
  56414. return InstancedMesh;
  56415. }(BABYLON.AbstractMesh));
  56416. BABYLON.InstancedMesh = InstancedMesh;
  56417. })(BABYLON || (BABYLON = {}));
  56418. //# sourceMappingURL=babylon.instancedMesh.js.map
  56419. "use strict";
  56420. var BABYLON;
  56421. (function (BABYLON) {
  56422. var LinesMesh = /** @class */ (function (_super) {
  56423. __extends(LinesMesh, _super);
  56424. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56425. if (scene === void 0) { scene = null; }
  56426. if (parent === void 0) { parent = null; }
  56427. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56428. _this.useVertexColor = useVertexColor;
  56429. _this.useVertexAlpha = useVertexAlpha;
  56430. _this.color = new BABYLON.Color3(1, 1, 1);
  56431. _this.alpha = 1;
  56432. if (source) {
  56433. _this.color = source.color.clone();
  56434. _this.alpha = source.alpha;
  56435. _this.useVertexColor = source.useVertexColor;
  56436. _this.useVertexAlpha = source.useVertexAlpha;
  56437. }
  56438. _this._intersectionThreshold = 0.1;
  56439. var defines = [];
  56440. var options = {
  56441. attributes: [BABYLON.VertexBuffer.PositionKind],
  56442. uniforms: ["world", "viewProjection"],
  56443. needAlphaBlending: true,
  56444. defines: defines
  56445. };
  56446. if (useVertexAlpha === false) {
  56447. options.needAlphaBlending = false;
  56448. }
  56449. if (!useVertexColor) {
  56450. options.uniforms.push("color");
  56451. }
  56452. else {
  56453. options.defines.push("#define VERTEXCOLOR");
  56454. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56455. }
  56456. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56457. return _this;
  56458. }
  56459. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56460. /**
  56461. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56462. * This margin is expressed in world space coordinates, so its value may vary.
  56463. * Default value is 0.1
  56464. * @returns the intersection Threshold value.
  56465. */
  56466. get: function () {
  56467. return this._intersectionThreshold;
  56468. },
  56469. /**
  56470. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56471. * This margin is expressed in world space coordinates, so its value may vary.
  56472. * @param value the new threshold to apply
  56473. */
  56474. set: function (value) {
  56475. if (this._intersectionThreshold === value) {
  56476. return;
  56477. }
  56478. this._intersectionThreshold = value;
  56479. if (this.geometry) {
  56480. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56481. }
  56482. },
  56483. enumerable: true,
  56484. configurable: true
  56485. });
  56486. /**
  56487. * Returns the string "LineMesh"
  56488. */
  56489. LinesMesh.prototype.getClassName = function () {
  56490. return "LinesMesh";
  56491. };
  56492. Object.defineProperty(LinesMesh.prototype, "material", {
  56493. get: function () {
  56494. return this._colorShader;
  56495. },
  56496. set: function (value) {
  56497. // Do nothing
  56498. },
  56499. enumerable: true,
  56500. configurable: true
  56501. });
  56502. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56503. get: function () {
  56504. return false;
  56505. },
  56506. enumerable: true,
  56507. configurable: true
  56508. });
  56509. LinesMesh.prototype.createInstance = function (name) {
  56510. throw new Error("LinesMeshes do not support createInstance.");
  56511. };
  56512. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56513. if (!this._geometry) {
  56514. return this;
  56515. }
  56516. // VBOs
  56517. this._geometry._bind(this._colorShader.getEffect());
  56518. // Color
  56519. if (!this.useVertexColor) {
  56520. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56521. }
  56522. return this;
  56523. };
  56524. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56525. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56526. return this;
  56527. }
  56528. var engine = this.getScene().getEngine();
  56529. // Draw order
  56530. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56531. return this;
  56532. };
  56533. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56534. this._colorShader.dispose();
  56535. _super.prototype.dispose.call(this, doNotRecurse);
  56536. };
  56537. /**
  56538. * Returns a new LineMesh object cloned from the current one.
  56539. */
  56540. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56541. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56542. };
  56543. return LinesMesh;
  56544. }(BABYLON.Mesh));
  56545. BABYLON.LinesMesh = LinesMesh;
  56546. })(BABYLON || (BABYLON = {}));
  56547. //# sourceMappingURL=babylon.linesMesh.js.map
  56548. "use strict";
  56549. var BABYLON;
  56550. (function (BABYLON) {
  56551. var MeshBuilder = /** @class */ (function () {
  56552. function MeshBuilder() {
  56553. }
  56554. MeshBuilder.updateSideOrientation = function (orientation) {
  56555. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56556. return BABYLON.Mesh.DOUBLESIDE;
  56557. }
  56558. if (orientation === undefined || orientation === null) {
  56559. return BABYLON.Mesh.FRONTSIDE;
  56560. }
  56561. return orientation;
  56562. };
  56563. /**
  56564. * Creates a box mesh.
  56565. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56566. * The parameter `size` sets the size (float) of each box side (default 1).
  56567. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56568. * 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).
  56569. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56571. * 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).
  56572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56574. */
  56575. MeshBuilder.CreateBox = function (name, options, scene) {
  56576. if (scene === void 0) { scene = null; }
  56577. var box = new BABYLON.Mesh(name, scene);
  56578. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56579. box._originalBuilderSideOrientation = options.sideOrientation;
  56580. var vertexData = BABYLON.VertexData.CreateBox(options);
  56581. vertexData.applyToMesh(box, options.updatable);
  56582. return box;
  56583. };
  56584. /**
  56585. * Creates a sphere mesh.
  56586. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56587. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56588. * 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`).
  56589. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56590. * 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
  56591. * 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).
  56592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56593. * 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).
  56594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56596. */
  56597. MeshBuilder.CreateSphere = function (name, options, scene) {
  56598. var sphere = new BABYLON.Mesh(name, scene);
  56599. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56600. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56601. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56602. vertexData.applyToMesh(sphere, options.updatable);
  56603. return sphere;
  56604. };
  56605. /**
  56606. * Creates a plane polygonal mesh. By default, this is a disc.
  56607. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56608. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56609. * 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.
  56610. * 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
  56611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56612. * 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).
  56613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56615. */
  56616. MeshBuilder.CreateDisc = function (name, options, scene) {
  56617. if (scene === void 0) { scene = null; }
  56618. var disc = new BABYLON.Mesh(name, scene);
  56619. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56620. disc._originalBuilderSideOrientation = options.sideOrientation;
  56621. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56622. vertexData.applyToMesh(disc, options.updatable);
  56623. return disc;
  56624. };
  56625. /**
  56626. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56627. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56628. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56629. * 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`).
  56630. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56631. * 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.
  56632. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56633. * 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).
  56634. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56635. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56636. */
  56637. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56638. var sphere = new BABYLON.Mesh(name, scene);
  56639. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56640. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56641. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56642. vertexData.applyToMesh(sphere, options.updatable);
  56643. return sphere;
  56644. };
  56645. ;
  56646. /**
  56647. * Creates a ribbon mesh.
  56648. * 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.
  56649. *
  56650. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56651. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56652. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56653. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56654. * 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.
  56655. * 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.
  56656. * 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
  56657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56658. * 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).
  56659. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56660. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56661. * 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.
  56662. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56663. * 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
  56664. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56665. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56667. */
  56668. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56669. if (scene === void 0) { scene = null; }
  56670. var pathArray = options.pathArray;
  56671. var closeArray = options.closeArray;
  56672. var closePath = options.closePath;
  56673. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56674. var instance = options.instance;
  56675. var updatable = options.updatable;
  56676. if (instance) {
  56677. // positionFunction : ribbon case
  56678. // only pathArray and sideOrientation parameters are taken into account for positions update
  56679. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56680. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56681. var positionFunction = function (positions) {
  56682. var minlg = pathArray[0].length;
  56683. var i = 0;
  56684. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56685. for (var si = 1; si <= ns; si++) {
  56686. for (var p = 0; p < pathArray.length; p++) {
  56687. var path = pathArray[p];
  56688. var l = path.length;
  56689. minlg = (minlg < l) ? minlg : l;
  56690. var j = 0;
  56691. while (j < minlg) {
  56692. positions[i] = path[j].x;
  56693. positions[i + 1] = path[j].y;
  56694. positions[i + 2] = path[j].z;
  56695. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56696. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56697. }
  56698. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56699. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56700. }
  56701. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56702. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56703. }
  56704. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56705. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56706. }
  56707. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56708. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56709. }
  56710. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56711. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56712. }
  56713. j++;
  56714. i += 3;
  56715. }
  56716. if (instance._closePath) {
  56717. positions[i] = path[0].x;
  56718. positions[i + 1] = path[0].y;
  56719. positions[i + 2] = path[0].z;
  56720. i += 3;
  56721. }
  56722. }
  56723. }
  56724. };
  56725. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56726. positionFunction(positions);
  56727. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56728. instance._boundingInfo.update(instance._worldMatrix);
  56729. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56730. if (options.colors) {
  56731. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56732. for (var c = 0; c < options.colors.length; c++) {
  56733. colors[c * 4] = options.colors[c].r;
  56734. colors[c * 4 + 1] = options.colors[c].g;
  56735. colors[c * 4 + 2] = options.colors[c].b;
  56736. colors[c * 4 + 3] = options.colors[c].a;
  56737. }
  56738. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56739. }
  56740. if (options.uvs) {
  56741. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56742. for (var i = 0; i < options.uvs.length; i++) {
  56743. uvs[i * 2] = options.uvs[i].x;
  56744. uvs[i * 2 + 1] = options.uvs[i].y;
  56745. }
  56746. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56747. }
  56748. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56749. var indices = instance.getIndices();
  56750. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56751. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56752. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56753. if (instance._closePath) {
  56754. var indexFirst = 0;
  56755. var indexLast = 0;
  56756. for (var p = 0; p < pathArray.length; p++) {
  56757. indexFirst = instance._idx[p] * 3;
  56758. if (p + 1 < pathArray.length) {
  56759. indexLast = (instance._idx[p + 1] - 1) * 3;
  56760. }
  56761. else {
  56762. indexLast = normals.length - 3;
  56763. }
  56764. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56765. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56766. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56767. normals[indexLast] = normals[indexFirst];
  56768. normals[indexLast + 1] = normals[indexFirst + 1];
  56769. normals[indexLast + 2] = normals[indexFirst + 2];
  56770. }
  56771. }
  56772. if (!(instance.areNormalsFrozen)) {
  56773. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56774. }
  56775. }
  56776. return instance;
  56777. }
  56778. else {
  56779. var ribbon = new BABYLON.Mesh(name, scene);
  56780. ribbon._originalBuilderSideOrientation = sideOrientation;
  56781. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56782. if (closePath) {
  56783. ribbon._idx = vertexData._idx;
  56784. }
  56785. ribbon._closePath = closePath;
  56786. ribbon._closeArray = closeArray;
  56787. vertexData.applyToMesh(ribbon, updatable);
  56788. return ribbon;
  56789. }
  56790. };
  56791. /**
  56792. * Creates a cylinder or a cone mesh.
  56793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56794. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56795. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56796. * 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.
  56797. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56798. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56799. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56800. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56801. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56802. * 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).
  56803. * 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
  56804. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56805. * 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
  56806. * 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.
  56807. * If `enclose` is false, a ring surface is one element.
  56808. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56809. * 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
  56810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56811. * 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).
  56812. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56814. */
  56815. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56816. var cylinder = new BABYLON.Mesh(name, scene);
  56817. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56818. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56819. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56820. vertexData.applyToMesh(cylinder, options.updatable);
  56821. return cylinder;
  56822. };
  56823. /**
  56824. * Creates a torus mesh.
  56825. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56826. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56827. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56828. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56830. * 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).
  56831. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56833. */
  56834. MeshBuilder.CreateTorus = function (name, options, scene) {
  56835. var torus = new BABYLON.Mesh(name, scene);
  56836. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56837. torus._originalBuilderSideOrientation = options.sideOrientation;
  56838. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56839. vertexData.applyToMesh(torus, options.updatable);
  56840. return torus;
  56841. };
  56842. /**
  56843. * Creates a torus knot mesh.
  56844. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56845. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56846. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56847. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56848. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56850. * 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).
  56851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56853. */
  56854. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56855. var torusKnot = new BABYLON.Mesh(name, scene);
  56856. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56857. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56858. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56859. vertexData.applyToMesh(torusKnot, options.updatable);
  56860. return torusKnot;
  56861. };
  56862. /**
  56863. * Creates a line system mesh.
  56864. * A line system is a pool of many lines gathered in a single mesh.
  56865. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56866. * 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.
  56867. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56868. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56869. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56870. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56871. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56872. * 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
  56873. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56875. */
  56876. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56877. var instance = options.instance;
  56878. var lines = options.lines;
  56879. var colors = options.colors;
  56880. if (instance) {
  56881. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56882. var vertexColor;
  56883. var lineColors;
  56884. if (colors) {
  56885. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56886. }
  56887. var i = 0;
  56888. var c = 0;
  56889. for (var l = 0; l < lines.length; l++) {
  56890. var points = lines[l];
  56891. for (var p = 0; p < points.length; p++) {
  56892. positions[i] = points[p].x;
  56893. positions[i + 1] = points[p].y;
  56894. positions[i + 2] = points[p].z;
  56895. if (colors && vertexColor) {
  56896. lineColors = colors[l];
  56897. vertexColor[c] = lineColors[p].r;
  56898. vertexColor[c + 1] = lineColors[p].g;
  56899. vertexColor[c + 2] = lineColors[p].b;
  56900. vertexColor[c + 3] = lineColors[p].a;
  56901. c += 4;
  56902. }
  56903. i += 3;
  56904. }
  56905. }
  56906. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56907. if (colors && vertexColor) {
  56908. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56909. }
  56910. return instance;
  56911. }
  56912. // line system creation
  56913. var useVertexColor = (colors) ? true : false;
  56914. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56915. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56916. vertexData.applyToMesh(lineSystem, options.updatable);
  56917. return lineSystem;
  56918. };
  56919. /**
  56920. * Creates a line mesh.
  56921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56922. * 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.
  56923. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56924. * The parameter `points` is an array successive Vector3.
  56925. * 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
  56926. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56927. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56928. * When updating an instance, remember that only point positions can change, not the number of points.
  56929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56930. */
  56931. MeshBuilder.CreateLines = function (name, options, scene) {
  56932. if (scene === void 0) { scene = null; }
  56933. var colors = (options.colors) ? [options.colors] : null;
  56934. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56935. return lines;
  56936. };
  56937. /**
  56938. * Creates a dashed line mesh.
  56939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56940. * 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.
  56941. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56942. * The parameter `points` is an array successive Vector3.
  56943. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56944. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56945. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56946. * 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
  56947. * When updating an instance, remember that only point positions can change, not the number of points.
  56948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56949. */
  56950. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56951. if (scene === void 0) { scene = null; }
  56952. var points = options.points;
  56953. var instance = options.instance;
  56954. var gapSize = options.gapSize || 1;
  56955. var dashSize = options.dashSize || 3;
  56956. if (instance) {
  56957. var positionFunction = function (positions) {
  56958. var curvect = BABYLON.Vector3.Zero();
  56959. var nbSeg = positions.length / 6;
  56960. var lg = 0;
  56961. var nb = 0;
  56962. var shft = 0;
  56963. var dashshft = 0;
  56964. var curshft = 0;
  56965. var p = 0;
  56966. var i = 0;
  56967. var j = 0;
  56968. for (i = 0; i < points.length - 1; i++) {
  56969. points[i + 1].subtractToRef(points[i], curvect);
  56970. lg += curvect.length();
  56971. }
  56972. shft = lg / nbSeg;
  56973. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56974. for (i = 0; i < points.length - 1; i++) {
  56975. points[i + 1].subtractToRef(points[i], curvect);
  56976. nb = Math.floor(curvect.length() / shft);
  56977. curvect.normalize();
  56978. j = 0;
  56979. while (j < nb && p < positions.length) {
  56980. curshft = shft * j;
  56981. positions[p] = points[i].x + curshft * curvect.x;
  56982. positions[p + 1] = points[i].y + curshft * curvect.y;
  56983. positions[p + 2] = points[i].z + curshft * curvect.z;
  56984. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56985. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56986. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56987. p += 6;
  56988. j++;
  56989. }
  56990. }
  56991. while (p < positions.length) {
  56992. positions[p] = points[i].x;
  56993. positions[p + 1] = points[i].y;
  56994. positions[p + 2] = points[i].z;
  56995. p += 3;
  56996. }
  56997. };
  56998. instance.updateMeshPositions(positionFunction, false);
  56999. return instance;
  57000. }
  57001. // dashed lines creation
  57002. var dashedLines = new BABYLON.LinesMesh(name, scene);
  57003. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  57004. vertexData.applyToMesh(dashedLines, options.updatable);
  57005. dashedLines.dashSize = dashSize;
  57006. dashedLines.gapSize = gapSize;
  57007. return dashedLines;
  57008. };
  57009. /**
  57010. * Creates an extruded shape mesh.
  57011. * 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.
  57012. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  57013. *
  57014. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57015. * 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
  57016. * extruded along the Z axis.
  57017. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57018. * 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.
  57019. * The parameter `scale` (float, default 1) is the value to scale the shape.
  57020. * 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
  57021. * 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
  57022. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57024. * 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).
  57025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57026. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57028. */
  57029. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  57030. if (scene === void 0) { scene = null; }
  57031. var path = options.path;
  57032. var shape = options.shape;
  57033. var scale = options.scale || 1;
  57034. var rotation = options.rotation || 0;
  57035. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57036. var updatable = options.updatable;
  57037. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57038. var instance = options.instance || null;
  57039. var invertUV = options.invertUV || false;
  57040. 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);
  57041. };
  57042. /**
  57043. * Creates an custom extruded shape mesh.
  57044. * 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.
  57045. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  57046. *
  57047. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57048. * 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
  57049. * extruded along the Z axis.
  57050. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57051. * 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
  57052. * and the distance of this point from the begining of the path :
  57053. * ```javascript
  57054. * var rotationFunction = function(i, distance) {
  57055. * // do things
  57056. * return rotationValue; }
  57057. * ```
  57058. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57059. * 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
  57060. * and the distance of this point from the begining of the path :
  57061. * ```javascript
  57062. * var scaleFunction = function(i, distance) {
  57063. * // do things
  57064. * return scaleValue;}
  57065. * ```
  57066. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57067. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57068. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57069. * 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
  57070. * 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
  57071. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57072. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57073. * 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).
  57074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57075. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57077. */
  57078. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57079. var path = options.path;
  57080. var shape = options.shape;
  57081. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57082. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57083. var ribbonCloseArray = options.ribbonCloseArray || false;
  57084. var ribbonClosePath = options.ribbonClosePath || false;
  57085. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57086. var updatable = options.updatable;
  57087. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57088. var instance = options.instance;
  57089. var invertUV = options.invertUV || false;
  57090. 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);
  57091. };
  57092. /**
  57093. * Creates lathe mesh.
  57094. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57095. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57096. *
  57097. * 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
  57098. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57099. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57100. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57101. * 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.
  57102. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57103. * 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
  57104. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57105. * 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).
  57106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57107. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57109. */
  57110. MeshBuilder.CreateLathe = function (name, options, scene) {
  57111. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57112. var closed = (options.closed === undefined) ? true : options.closed;
  57113. var shape = options.shape;
  57114. var radius = options.radius || 1;
  57115. var tessellation = options.tessellation || 64;
  57116. var updatable = options.updatable;
  57117. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57118. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57119. var pi2 = Math.PI * 2;
  57120. var paths = new Array();
  57121. var invertUV = options.invertUV || false;
  57122. var i = 0;
  57123. var p = 0;
  57124. var step = pi2 / tessellation * arc;
  57125. var rotated;
  57126. var path = new Array();
  57127. ;
  57128. for (i = 0; i <= tessellation; i++) {
  57129. var path = [];
  57130. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57131. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57132. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57133. }
  57134. for (p = 0; p < shape.length; p++) {
  57135. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57136. path.push(rotated);
  57137. }
  57138. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57139. 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));
  57140. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57141. }
  57142. paths.push(path);
  57143. }
  57144. // lathe ribbon
  57145. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57146. return lathe;
  57147. };
  57148. /**
  57149. * Creates a plane mesh.
  57150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57151. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57152. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57153. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57154. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57155. * 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).
  57156. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57158. */
  57159. MeshBuilder.CreatePlane = function (name, options, scene) {
  57160. var plane = new BABYLON.Mesh(name, scene);
  57161. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57162. plane._originalBuilderSideOrientation = options.sideOrientation;
  57163. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57164. vertexData.applyToMesh(plane, options.updatable);
  57165. if (options.sourcePlane) {
  57166. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57167. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57168. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57169. plane.rotate(vectorProduct, product);
  57170. }
  57171. return plane;
  57172. };
  57173. /**
  57174. * Creates a ground mesh.
  57175. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57176. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57177. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57179. */
  57180. MeshBuilder.CreateGround = function (name, options, scene) {
  57181. var ground = new BABYLON.GroundMesh(name, scene);
  57182. ground._setReady(false);
  57183. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57184. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57185. ground._width = options.width || 1;
  57186. ground._height = options.height || 1;
  57187. ground._maxX = ground._width / 2;
  57188. ground._maxZ = ground._height / 2;
  57189. ground._minX = -ground._maxX;
  57190. ground._minZ = -ground._maxZ;
  57191. var vertexData = BABYLON.VertexData.CreateGround(options);
  57192. vertexData.applyToMesh(ground, options.updatable);
  57193. ground._setReady(true);
  57194. return ground;
  57195. };
  57196. /**
  57197. * Creates a tiled ground mesh.
  57198. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57199. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57200. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57201. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57202. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57203. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57204. * numbers of subdivisions on the ground width and height of each tile.
  57205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57206. */
  57207. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57208. var tiledGround = new BABYLON.Mesh(name, scene);
  57209. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57210. vertexData.applyToMesh(tiledGround, options.updatable);
  57211. return tiledGround;
  57212. };
  57213. /**
  57214. * Creates a ground mesh from a height map.
  57215. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57216. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57217. * The parameter `url` sets the URL of the height map image resource.
  57218. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57219. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57220. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57221. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57222. * 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.
  57223. * 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).
  57224. * This function is passed the newly built mesh :
  57225. * ```javascript
  57226. * function(mesh) { // do things
  57227. * return; }
  57228. * ```
  57229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57230. */
  57231. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57232. var width = options.width || 10.0;
  57233. var height = options.height || 10.0;
  57234. var subdivisions = options.subdivisions || 1 | 0;
  57235. var minHeight = options.minHeight || 0.0;
  57236. var maxHeight = options.maxHeight || 1.0;
  57237. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57238. var updatable = options.updatable;
  57239. var onReady = options.onReady;
  57240. var ground = new BABYLON.GroundMesh(name, scene);
  57241. ground._subdivisionsX = subdivisions;
  57242. ground._subdivisionsY = subdivisions;
  57243. ground._width = width;
  57244. ground._height = height;
  57245. ground._maxX = ground._width / 2.0;
  57246. ground._maxZ = ground._height / 2.0;
  57247. ground._minX = -ground._maxX;
  57248. ground._minZ = -ground._maxZ;
  57249. ground._setReady(false);
  57250. var onload = function (img) {
  57251. // Getting height map data
  57252. var canvas = document.createElement("canvas");
  57253. var context = canvas.getContext("2d");
  57254. if (!context) {
  57255. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57256. }
  57257. if (scene.isDisposed) {
  57258. return;
  57259. }
  57260. var bufferWidth = img.width;
  57261. var bufferHeight = img.height;
  57262. canvas.width = bufferWidth;
  57263. canvas.height = bufferHeight;
  57264. context.drawImage(img, 0, 0);
  57265. // Create VertexData from map data
  57266. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57267. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57268. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57269. width: width, height: height,
  57270. subdivisions: subdivisions,
  57271. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57272. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57273. });
  57274. vertexData.applyToMesh(ground, updatable);
  57275. //execute ready callback, if set
  57276. if (onReady) {
  57277. onReady(ground);
  57278. }
  57279. ground._setReady(true);
  57280. };
  57281. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57282. return ground;
  57283. };
  57284. /**
  57285. * Creates a polygon mesh.
  57286. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57287. * 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.
  57288. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57290. * 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).
  57291. * Remember you can only change the shape positions, not their number when updating a polygon.
  57292. */
  57293. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57294. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57295. var shape = options.shape;
  57296. var holes = options.holes || [];
  57297. var depth = options.depth || 0;
  57298. var contours = [];
  57299. var hole = [];
  57300. for (var i = 0; i < shape.length; i++) {
  57301. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57302. }
  57303. var epsilon = 0.00000001;
  57304. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57305. contours.pop();
  57306. }
  57307. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57308. for (var hNb = 0; hNb < holes.length; hNb++) {
  57309. hole = [];
  57310. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57311. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57312. }
  57313. polygonTriangulation.addHole(hole);
  57314. }
  57315. var polygon = polygonTriangulation.build(options.updatable, depth);
  57316. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57317. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57318. vertexData.applyToMesh(polygon, options.updatable);
  57319. return polygon;
  57320. };
  57321. ;
  57322. /**
  57323. * Creates an extruded polygon mesh, with depth in the Y direction.
  57324. * 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).
  57325. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57326. */
  57327. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57328. return MeshBuilder.CreatePolygon(name, options, scene);
  57329. };
  57330. ;
  57331. /**
  57332. * Creates a tube mesh.
  57333. * 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.
  57334. *
  57335. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57336. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57337. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57338. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57339. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57340. * 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.
  57341. * It must return a radius value (positive float) :
  57342. * ```javascript
  57343. * var radiusFunction = function(i, distance) {
  57344. * // do things
  57345. * return radius; }
  57346. * ```
  57347. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57348. * 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
  57349. * 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
  57350. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57351. * 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).
  57352. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57353. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57355. */
  57356. MeshBuilder.CreateTube = function (name, options, scene) {
  57357. var path = options.path;
  57358. var instance = options.instance;
  57359. var radius = 1.0;
  57360. if (instance) {
  57361. radius = instance.radius;
  57362. }
  57363. if (options.radius !== undefined) {
  57364. radius = options.radius;
  57365. }
  57366. ;
  57367. var tessellation = options.tessellation || 64 | 0;
  57368. var radiusFunction = options.radiusFunction || null;
  57369. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57370. var invertUV = options.invertUV || false;
  57371. var updatable = options.updatable;
  57372. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57373. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57374. // tube geometry
  57375. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57376. var tangents = path3D.getTangents();
  57377. var normals = path3D.getNormals();
  57378. var distances = path3D.getDistances();
  57379. var pi2 = Math.PI * 2;
  57380. var step = pi2 / tessellation * arc;
  57381. var returnRadius = function () { return radius; };
  57382. var radiusFunctionFinal = radiusFunction || returnRadius;
  57383. var circlePath;
  57384. var rad;
  57385. var normal;
  57386. var rotated;
  57387. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57388. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57389. for (var i = 0; i < path.length; i++) {
  57390. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57391. circlePath = Array(); // current circle array
  57392. normal = normals[i]; // current normal
  57393. for (var t = 0; t < tessellation; t++) {
  57394. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57395. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57396. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57397. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57398. circlePath[t] = rotated;
  57399. }
  57400. circlePaths[index] = circlePath;
  57401. index++;
  57402. }
  57403. // cap
  57404. var capPath = function (nbPoints, pathIndex) {
  57405. var pointCap = Array();
  57406. for (var i = 0; i < nbPoints; i++) {
  57407. pointCap.push(path[pathIndex]);
  57408. }
  57409. return pointCap;
  57410. };
  57411. switch (cap) {
  57412. case BABYLON.Mesh.NO_CAP:
  57413. break;
  57414. case BABYLON.Mesh.CAP_START:
  57415. circlePaths[0] = capPath(tessellation, 0);
  57416. circlePaths[1] = circlePaths[2].slice(0);
  57417. break;
  57418. case BABYLON.Mesh.CAP_END:
  57419. circlePaths[index] = circlePaths[index - 1].slice(0);
  57420. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57421. break;
  57422. case BABYLON.Mesh.CAP_ALL:
  57423. circlePaths[0] = capPath(tessellation, 0);
  57424. circlePaths[1] = circlePaths[2].slice(0);
  57425. circlePaths[index] = circlePaths[index - 1].slice(0);
  57426. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57427. break;
  57428. default:
  57429. break;
  57430. }
  57431. return circlePaths;
  57432. };
  57433. var path3D;
  57434. var pathArray;
  57435. if (instance) {
  57436. var arc = options.arc || instance.arc;
  57437. path3D = (instance.path3D).update(path);
  57438. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57439. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57440. instance.path3D = path3D;
  57441. instance.pathArray = pathArray;
  57442. instance.arc = arc;
  57443. instance.radius = radius;
  57444. return instance;
  57445. }
  57446. // tube creation
  57447. path3D = new BABYLON.Path3D(path);
  57448. var newPathArray = new Array();
  57449. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57450. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57451. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57452. tube.pathArray = pathArray;
  57453. tube.path3D = path3D;
  57454. tube.tessellation = tessellation;
  57455. tube.cap = cap;
  57456. tube.arc = options.arc;
  57457. tube.radius = radius;
  57458. return tube;
  57459. };
  57460. /**
  57461. * Creates a polyhedron mesh.
  57462. *
  57463. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57464. * 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
  57465. * to choose the wanted type.
  57466. * The parameter `size` (positive float, default 1) sets the polygon size.
  57467. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57468. * 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`.
  57469. * 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
  57470. * 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)`).
  57471. * 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
  57472. * 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.
  57473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57474. * 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).
  57475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57477. */
  57478. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57479. var polyhedron = new BABYLON.Mesh(name, scene);
  57480. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57481. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57482. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57483. vertexData.applyToMesh(polyhedron, options.updatable);
  57484. return polyhedron;
  57485. };
  57486. /**
  57487. * Creates a decal mesh.
  57488. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57489. * 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.
  57490. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57491. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57492. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57493. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57494. */
  57495. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57496. var indices = sourceMesh.getIndices();
  57497. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57498. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57499. var position = options.position || BABYLON.Vector3.Zero();
  57500. var normal = options.normal || BABYLON.Vector3.Up();
  57501. var size = options.size || BABYLON.Vector3.One();
  57502. var angle = options.angle || 0;
  57503. // Getting correct rotation
  57504. if (!normal) {
  57505. var target = new BABYLON.Vector3(0, 0, 1);
  57506. var camera = sourceMesh.getScene().activeCamera;
  57507. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57508. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57509. }
  57510. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57511. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57512. var pitch = Math.atan2(normal.y, len);
  57513. // Matrix
  57514. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57515. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57516. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57517. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57518. var vertexData = new BABYLON.VertexData();
  57519. vertexData.indices = [];
  57520. vertexData.positions = [];
  57521. vertexData.normals = [];
  57522. vertexData.uvs = [];
  57523. var currentVertexDataIndex = 0;
  57524. var extractDecalVector3 = function (indexId) {
  57525. var result = new BABYLON.PositionNormalVertex();
  57526. if (!indices || !positions || !normals) {
  57527. return result;
  57528. }
  57529. var vertexId = indices[indexId];
  57530. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57531. // Send vector to decal local world
  57532. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57533. // Get normal
  57534. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57535. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57536. return result;
  57537. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57538. var clip = function (vertices, axis) {
  57539. if (vertices.length === 0) {
  57540. return vertices;
  57541. }
  57542. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57543. var clipVertices = function (v0, v1) {
  57544. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57545. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57546. };
  57547. var result = new Array();
  57548. for (var index = 0; index < vertices.length; index += 3) {
  57549. var v1Out;
  57550. var v2Out;
  57551. var v3Out;
  57552. var total = 0;
  57553. var nV1 = null;
  57554. var nV2 = null;
  57555. var nV3 = null;
  57556. var nV4 = null;
  57557. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57558. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57559. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57560. v1Out = d1 > 0;
  57561. v2Out = d2 > 0;
  57562. v3Out = d3 > 0;
  57563. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57564. switch (total) {
  57565. case 0:
  57566. result.push(vertices[index]);
  57567. result.push(vertices[index + 1]);
  57568. result.push(vertices[index + 2]);
  57569. break;
  57570. case 1:
  57571. if (v1Out) {
  57572. nV1 = vertices[index + 1];
  57573. nV2 = vertices[index + 2];
  57574. nV3 = clipVertices(vertices[index], nV1);
  57575. nV4 = clipVertices(vertices[index], nV2);
  57576. }
  57577. if (v2Out) {
  57578. nV1 = vertices[index];
  57579. nV2 = vertices[index + 2];
  57580. nV3 = clipVertices(vertices[index + 1], nV1);
  57581. nV4 = clipVertices(vertices[index + 1], nV2);
  57582. result.push(nV3);
  57583. result.push(nV2.clone());
  57584. result.push(nV1.clone());
  57585. result.push(nV2.clone());
  57586. result.push(nV3.clone());
  57587. result.push(nV4);
  57588. break;
  57589. }
  57590. if (v3Out) {
  57591. nV1 = vertices[index];
  57592. nV2 = vertices[index + 1];
  57593. nV3 = clipVertices(vertices[index + 2], nV1);
  57594. nV4 = clipVertices(vertices[index + 2], nV2);
  57595. }
  57596. if (nV1 && nV2 && nV3 && nV4) {
  57597. result.push(nV1.clone());
  57598. result.push(nV2.clone());
  57599. result.push(nV3);
  57600. result.push(nV4);
  57601. result.push(nV3.clone());
  57602. result.push(nV2.clone());
  57603. }
  57604. break;
  57605. case 2:
  57606. if (!v1Out) {
  57607. nV1 = vertices[index].clone();
  57608. nV2 = clipVertices(nV1, vertices[index + 1]);
  57609. nV3 = clipVertices(nV1, vertices[index + 2]);
  57610. result.push(nV1);
  57611. result.push(nV2);
  57612. result.push(nV3);
  57613. }
  57614. if (!v2Out) {
  57615. nV1 = vertices[index + 1].clone();
  57616. nV2 = clipVertices(nV1, vertices[index + 2]);
  57617. nV3 = clipVertices(nV1, vertices[index]);
  57618. result.push(nV1);
  57619. result.push(nV2);
  57620. result.push(nV3);
  57621. }
  57622. if (!v3Out) {
  57623. nV1 = vertices[index + 2].clone();
  57624. nV2 = clipVertices(nV1, vertices[index]);
  57625. nV3 = clipVertices(nV1, vertices[index + 1]);
  57626. result.push(nV1);
  57627. result.push(nV2);
  57628. result.push(nV3);
  57629. }
  57630. break;
  57631. case 3:
  57632. break;
  57633. }
  57634. }
  57635. return result;
  57636. };
  57637. for (var index = 0; index < indices.length; index += 3) {
  57638. var faceVertices = new Array();
  57639. faceVertices.push(extractDecalVector3(index));
  57640. faceVertices.push(extractDecalVector3(index + 1));
  57641. faceVertices.push(extractDecalVector3(index + 2));
  57642. // Clip
  57643. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57644. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57645. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57646. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57647. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57648. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57649. if (faceVertices.length === 0) {
  57650. continue;
  57651. }
  57652. // Add UVs and get back to world
  57653. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57654. var vertex = faceVertices[vIndex];
  57655. //TODO check for Int32Array | Uint32Array | Uint16Array
  57656. vertexData.indices.push(currentVertexDataIndex);
  57657. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57658. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57659. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57660. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57661. currentVertexDataIndex++;
  57662. }
  57663. }
  57664. // Return mesh
  57665. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57666. vertexData.applyToMesh(decal);
  57667. decal.position = position.clone();
  57668. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57669. return decal;
  57670. };
  57671. // Privates
  57672. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57673. // extrusion geometry
  57674. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57675. var tangents = path3D.getTangents();
  57676. var normals = path3D.getNormals();
  57677. var binormals = path3D.getBinormals();
  57678. var distances = path3D.getDistances();
  57679. var angle = 0;
  57680. var returnScale = function () { return scale !== null ? scale : 1; };
  57681. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57682. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57683. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57684. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57685. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57686. for (var i = 0; i < curve.length; i++) {
  57687. var shapePath = new Array();
  57688. var angleStep = rotate(i, distances[i]);
  57689. var scaleRatio = scl(i, distances[i]);
  57690. for (var p = 0; p < shape.length; p++) {
  57691. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57692. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57693. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57694. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57695. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57696. shapePath[p] = rotated;
  57697. }
  57698. shapePaths[index] = shapePath;
  57699. angle += angleStep;
  57700. index++;
  57701. }
  57702. // cap
  57703. var capPath = function (shapePath) {
  57704. var pointCap = Array();
  57705. var barycenter = BABYLON.Vector3.Zero();
  57706. var i;
  57707. for (i = 0; i < shapePath.length; i++) {
  57708. barycenter.addInPlace(shapePath[i]);
  57709. }
  57710. barycenter.scaleInPlace(1.0 / shapePath.length);
  57711. for (i = 0; i < shapePath.length; i++) {
  57712. pointCap.push(barycenter);
  57713. }
  57714. return pointCap;
  57715. };
  57716. switch (cap) {
  57717. case BABYLON.Mesh.NO_CAP:
  57718. break;
  57719. case BABYLON.Mesh.CAP_START:
  57720. shapePaths[0] = capPath(shapePaths[2]);
  57721. shapePaths[1] = shapePaths[2];
  57722. break;
  57723. case BABYLON.Mesh.CAP_END:
  57724. shapePaths[index] = shapePaths[index - 1];
  57725. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57726. break;
  57727. case BABYLON.Mesh.CAP_ALL:
  57728. shapePaths[0] = capPath(shapePaths[2]);
  57729. shapePaths[1] = shapePaths[2];
  57730. shapePaths[index] = shapePaths[index - 1];
  57731. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57732. break;
  57733. default:
  57734. break;
  57735. }
  57736. return shapePaths;
  57737. };
  57738. var path3D;
  57739. var pathArray;
  57740. if (instance) {
  57741. path3D = (instance.path3D).update(curve);
  57742. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57743. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57744. return instance;
  57745. }
  57746. // extruded shape creation
  57747. path3D = new BABYLON.Path3D(curve);
  57748. var newShapePaths = new Array();
  57749. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57750. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57751. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57752. extrudedGeneric.pathArray = pathArray;
  57753. extrudedGeneric.path3D = path3D;
  57754. extrudedGeneric.cap = cap;
  57755. return extrudedGeneric;
  57756. };
  57757. return MeshBuilder;
  57758. }());
  57759. BABYLON.MeshBuilder = MeshBuilder;
  57760. })(BABYLON || (BABYLON = {}));
  57761. //# sourceMappingURL=babylon.meshBuilder.js.map
  57762. "use strict";
  57763. var BABYLON;
  57764. (function (BABYLON) {
  57765. /**
  57766. * Draco compression (https://google.github.io/draco/)
  57767. */
  57768. var DracoCompression = /** @class */ (function () {
  57769. /**
  57770. * Constructor
  57771. * @param numWorkers The number of workers for async operations
  57772. */
  57773. function DracoCompression(numWorkers) {
  57774. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57775. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57776. if (!workerBlobUrl || !Worker) {
  57777. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57778. return;
  57779. }
  57780. var workers = new Array(numWorkers);
  57781. for (var i = 0; i < workers.length; i++) {
  57782. var worker = new Worker(workerBlobUrl);
  57783. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57784. workers[i] = worker;
  57785. }
  57786. this._workerPool = new BABYLON.WorkerPool(workers);
  57787. }
  57788. /**
  57789. * Stop all async operations and release resources.
  57790. */
  57791. DracoCompression.prototype.dispose = function () {
  57792. this._workerPool.dispose();
  57793. delete this._workerPool;
  57794. };
  57795. /**
  57796. * Decode Draco compressed mesh data to vertex data.
  57797. * @param data The array buffer view for the Draco compression data
  57798. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57799. * @returns A promise that resolves with the decoded vertex data
  57800. */
  57801. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57802. var _this = this;
  57803. return new Promise(function (resolve, reject) {
  57804. _this._workerPool.push(function (worker, onComplete) {
  57805. var vertexData = new BABYLON.VertexData();
  57806. var onError = function (error) {
  57807. worker.removeEventListener("error", onError);
  57808. worker.removeEventListener("message", onMessage);
  57809. reject(error);
  57810. onComplete();
  57811. };
  57812. var onMessage = function (message) {
  57813. if (message.data === "done") {
  57814. worker.removeEventListener("error", onError);
  57815. worker.removeEventListener("message", onMessage);
  57816. resolve(vertexData);
  57817. onComplete();
  57818. }
  57819. else if (message.data.id === "indices") {
  57820. vertexData.indices = message.data.value;
  57821. }
  57822. else {
  57823. vertexData.set(message.data.value, message.data.id);
  57824. }
  57825. };
  57826. worker.addEventListener("error", onError);
  57827. worker.addEventListener("message", onMessage);
  57828. var dataCopy = new Uint8Array(data.byteLength);
  57829. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57830. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57831. });
  57832. });
  57833. };
  57834. /**
  57835. * The worker function that gets converted to a blob url to pass into a worker.
  57836. */
  57837. DracoCompression._Worker = function () {
  57838. // self is actually a DedicatedWorkerGlobalScope
  57839. var _self = self;
  57840. var decodeMesh = function (data, attributes) {
  57841. var dracoModule = new DracoDecoderModule();
  57842. var buffer = new dracoModule.DecoderBuffer();
  57843. buffer.Init(data, data.byteLength);
  57844. var decoder = new dracoModule.Decoder();
  57845. var geometry;
  57846. var status;
  57847. try {
  57848. var type = decoder.GetEncodedGeometryType(buffer);
  57849. switch (type) {
  57850. case dracoModule.TRIANGULAR_MESH:
  57851. geometry = new dracoModule.Mesh();
  57852. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57853. break;
  57854. case dracoModule.POINT_CLOUD:
  57855. geometry = new dracoModule.PointCloud();
  57856. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57857. break;
  57858. default:
  57859. throw new Error("Invalid geometry type " + type);
  57860. }
  57861. if (!status.ok() || !geometry.ptr) {
  57862. throw new Error(status.error_msg());
  57863. }
  57864. var numPoints = geometry.num_points();
  57865. if (type === dracoModule.TRIANGULAR_MESH) {
  57866. var numFaces = geometry.num_faces();
  57867. var faceIndices = new dracoModule.DracoInt32Array();
  57868. try {
  57869. var indices = new Uint32Array(numFaces * 3);
  57870. for (var i = 0; i < numFaces; i++) {
  57871. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57872. var offset = i * 3;
  57873. indices[offset + 0] = faceIndices.GetValue(0);
  57874. indices[offset + 1] = faceIndices.GetValue(1);
  57875. indices[offset + 2] = faceIndices.GetValue(2);
  57876. }
  57877. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57878. }
  57879. finally {
  57880. dracoModule.destroy(faceIndices);
  57881. }
  57882. }
  57883. for (var kind in attributes) {
  57884. var uniqueId = attributes[kind];
  57885. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57886. var dracoData = new dracoModule.DracoFloat32Array();
  57887. try {
  57888. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57889. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57890. for (var i = 0; i < babylonData.length; i++) {
  57891. babylonData[i] = dracoData.GetValue(i);
  57892. }
  57893. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57894. }
  57895. finally {
  57896. dracoModule.destroy(dracoData);
  57897. }
  57898. }
  57899. }
  57900. finally {
  57901. if (geometry) {
  57902. dracoModule.destroy(geometry);
  57903. }
  57904. dracoModule.destroy(decoder);
  57905. dracoModule.destroy(buffer);
  57906. }
  57907. _self.postMessage("done");
  57908. };
  57909. _self.onmessage = function (event) {
  57910. switch (event.data.id) {
  57911. case "initDecoder": {
  57912. importScripts(event.data.url);
  57913. break;
  57914. }
  57915. case "decodeMesh": {
  57916. decodeMesh(event.data.data, event.data.attributes);
  57917. break;
  57918. }
  57919. }
  57920. };
  57921. };
  57922. DracoCompression._GetDefaultDecoderUrl = function () {
  57923. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57924. return null;
  57925. }
  57926. for (var i = 0; i < document.scripts.length; i++) {
  57927. if (document.scripts[i].type === "text/x-draco-decoder") {
  57928. return document.scripts[i].src;
  57929. }
  57930. }
  57931. return null;
  57932. };
  57933. /**
  57934. * Gets the url to the draco decoder if available.
  57935. */
  57936. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57937. return DracoCompression;
  57938. }());
  57939. BABYLON.DracoCompression = DracoCompression;
  57940. })(BABYLON || (BABYLON = {}));
  57941. //# sourceMappingURL=babylon.dracoCompression.js.map
  57942. "use strict";
  57943. var BABYLON;
  57944. (function (BABYLON) {
  57945. var AudioEngine = /** @class */ (function () {
  57946. function AudioEngine() {
  57947. this._audioContext = null;
  57948. this._audioContextInitialized = false;
  57949. this.canUseWebAudio = false;
  57950. this.WarnedWebAudioUnsupported = false;
  57951. this.unlocked = false;
  57952. this.isMP3supported = false;
  57953. this.isOGGsupported = false;
  57954. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57955. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57956. this.canUseWebAudio = true;
  57957. }
  57958. var audioElem = document.createElement('audio');
  57959. try {
  57960. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57961. this.isMP3supported = true;
  57962. }
  57963. }
  57964. catch (e) {
  57965. // protect error during capability check.
  57966. }
  57967. try {
  57968. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57969. this.isOGGsupported = true;
  57970. }
  57971. }
  57972. catch (e) {
  57973. // protect error during capability check.
  57974. }
  57975. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57976. this._unlockiOSaudio();
  57977. }
  57978. else {
  57979. this.unlocked = true;
  57980. }
  57981. }
  57982. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57983. get: function () {
  57984. if (!this._audioContextInitialized) {
  57985. this._initializeAudioContext();
  57986. }
  57987. return this._audioContext;
  57988. },
  57989. enumerable: true,
  57990. configurable: true
  57991. });
  57992. AudioEngine.prototype._unlockiOSaudio = function () {
  57993. var _this = this;
  57994. var unlockaudio = function () {
  57995. if (!_this.audioContext) {
  57996. return;
  57997. }
  57998. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57999. var source = _this.audioContext.createBufferSource();
  58000. source.buffer = buffer;
  58001. source.connect(_this.audioContext.destination);
  58002. source.start(0);
  58003. setTimeout(function () {
  58004. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  58005. _this.unlocked = true;
  58006. window.removeEventListener('touchend', unlockaudio, false);
  58007. if (_this.onAudioUnlocked) {
  58008. _this.onAudioUnlocked();
  58009. }
  58010. }
  58011. }, 0);
  58012. };
  58013. window.addEventListener('touchend', unlockaudio, false);
  58014. };
  58015. AudioEngine.prototype._initializeAudioContext = function () {
  58016. try {
  58017. if (this.canUseWebAudio) {
  58018. this._audioContext = new AudioContext();
  58019. // create a global volume gain node
  58020. this.masterGain = this._audioContext.createGain();
  58021. this.masterGain.gain.value = 1;
  58022. this.masterGain.connect(this._audioContext.destination);
  58023. this._audioContextInitialized = true;
  58024. }
  58025. }
  58026. catch (e) {
  58027. this.canUseWebAudio = false;
  58028. BABYLON.Tools.Error("Web Audio: " + e.message);
  58029. }
  58030. };
  58031. AudioEngine.prototype.dispose = function () {
  58032. if (this.canUseWebAudio && this._audioContextInitialized) {
  58033. if (this._connectedAnalyser && this._audioContext) {
  58034. this._connectedAnalyser.stopDebugCanvas();
  58035. this._connectedAnalyser.dispose();
  58036. this.masterGain.disconnect();
  58037. this.masterGain.connect(this._audioContext.destination);
  58038. this._connectedAnalyser = null;
  58039. }
  58040. this.masterGain.gain.value = 1;
  58041. }
  58042. this.WarnedWebAudioUnsupported = false;
  58043. };
  58044. AudioEngine.prototype.getGlobalVolume = function () {
  58045. if (this.canUseWebAudio && this._audioContextInitialized) {
  58046. return this.masterGain.gain.value;
  58047. }
  58048. else {
  58049. return -1;
  58050. }
  58051. };
  58052. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58053. if (this.canUseWebAudio && this._audioContextInitialized) {
  58054. this.masterGain.gain.value = newVolume;
  58055. }
  58056. };
  58057. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58058. if (this._connectedAnalyser) {
  58059. this._connectedAnalyser.stopDebugCanvas();
  58060. }
  58061. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58062. this._connectedAnalyser = analyser;
  58063. this.masterGain.disconnect();
  58064. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58065. }
  58066. };
  58067. return AudioEngine;
  58068. }());
  58069. BABYLON.AudioEngine = AudioEngine;
  58070. })(BABYLON || (BABYLON = {}));
  58071. //# sourceMappingURL=babylon.audioEngine.js.map
  58072. "use strict";
  58073. var BABYLON;
  58074. (function (BABYLON) {
  58075. var Sound = /** @class */ (function () {
  58076. /**
  58077. * Create a sound and attach it to a scene
  58078. * @param name Name of your sound
  58079. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58080. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58081. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58082. */
  58083. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58084. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58085. var _this = this;
  58086. this.autoplay = false;
  58087. this.loop = false;
  58088. this.useCustomAttenuation = false;
  58089. this.spatialSound = false;
  58090. this.refDistance = 1;
  58091. this.rolloffFactor = 1;
  58092. this.maxDistance = 100;
  58093. this.distanceModel = "linear";
  58094. this._panningModel = "equalpower";
  58095. this._playbackRate = 1;
  58096. this._streaming = false;
  58097. this._startTime = 0;
  58098. this._startOffset = 0;
  58099. this._position = BABYLON.Vector3.Zero();
  58100. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58101. this._volume = 1;
  58102. this._isReadyToPlay = false;
  58103. this.isPlaying = false;
  58104. this.isPaused = false;
  58105. this._isDirectional = false;
  58106. // Used if you'd like to create a directional sound.
  58107. // If not set, the sound will be omnidirectional
  58108. this._coneInnerAngle = 360;
  58109. this._coneOuterAngle = 360;
  58110. this._coneOuterGain = 0;
  58111. this._isOutputConnected = false;
  58112. this._urlType = "Unknown";
  58113. this.name = name;
  58114. this._scene = scene;
  58115. this._readyToPlayCallback = readyToPlayCallback;
  58116. // Default custom attenuation function is a linear attenuation
  58117. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58118. if (currentDistance < maxDistance) {
  58119. return currentVolume * (1 - currentDistance / maxDistance);
  58120. }
  58121. else {
  58122. return 0;
  58123. }
  58124. };
  58125. if (options) {
  58126. this.autoplay = options.autoplay || false;
  58127. this.loop = options.loop || false;
  58128. // if volume === 0, we need another way to check this option
  58129. if (options.volume !== undefined) {
  58130. this._volume = options.volume;
  58131. }
  58132. this.spatialSound = options.spatialSound || false;
  58133. this.maxDistance = options.maxDistance || 100;
  58134. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58135. this.rolloffFactor = options.rolloffFactor || 1;
  58136. this.refDistance = options.refDistance || 1;
  58137. this.distanceModel = options.distanceModel || "linear";
  58138. this._playbackRate = options.playbackRate || 1;
  58139. this._streaming = options.streaming || false;
  58140. }
  58141. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58142. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58143. this._soundGain.gain.value = this._volume;
  58144. this._inputAudioNode = this._soundGain;
  58145. this._ouputAudioNode = this._soundGain;
  58146. if (this.spatialSound) {
  58147. this._createSpatialParameters();
  58148. }
  58149. this._scene.mainSoundTrack.AddSound(this);
  58150. var validParameter = true;
  58151. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58152. if (urlOrArrayBuffer) {
  58153. try {
  58154. if (typeof (urlOrArrayBuffer) === "string")
  58155. this._urlType = "String";
  58156. if (Array.isArray(urlOrArrayBuffer))
  58157. this._urlType = "Array";
  58158. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58159. this._urlType = "ArrayBuffer";
  58160. var urls = [];
  58161. var codecSupportedFound = false;
  58162. switch (this._urlType) {
  58163. case "ArrayBuffer":
  58164. if (urlOrArrayBuffer.byteLength > 0) {
  58165. codecSupportedFound = true;
  58166. this._soundLoaded(urlOrArrayBuffer);
  58167. }
  58168. break;
  58169. case "String":
  58170. urls.push(urlOrArrayBuffer);
  58171. case "Array":
  58172. if (urls.length === 0)
  58173. urls = urlOrArrayBuffer;
  58174. // If we found a supported format, we load it immediately and stop the loop
  58175. for (var i = 0; i < urls.length; i++) {
  58176. var url = urls[i];
  58177. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58178. codecSupportedFound = true;
  58179. }
  58180. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58181. codecSupportedFound = true;
  58182. }
  58183. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58184. codecSupportedFound = true;
  58185. }
  58186. if (url.indexOf("blob:") !== -1) {
  58187. codecSupportedFound = true;
  58188. }
  58189. if (codecSupportedFound) {
  58190. // Loading sound using XHR2
  58191. if (!this._streaming) {
  58192. this._scene._loadFile(url, function (data) {
  58193. _this._soundLoaded(data);
  58194. }, undefined, true, true, function (exception) {
  58195. if (exception) {
  58196. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58197. }
  58198. BABYLON.Tools.Error("Sound creation aborted.");
  58199. _this._scene.mainSoundTrack.RemoveSound(_this);
  58200. });
  58201. }
  58202. else {
  58203. this._htmlAudioElement = new Audio(url);
  58204. this._htmlAudioElement.controls = false;
  58205. this._htmlAudioElement.loop = this.loop;
  58206. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58207. this._htmlAudioElement.preload = "auto";
  58208. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58209. _this._isReadyToPlay = true;
  58210. if (_this.autoplay) {
  58211. _this.play();
  58212. }
  58213. if (_this._readyToPlayCallback) {
  58214. _this._readyToPlayCallback();
  58215. }
  58216. });
  58217. document.body.appendChild(this._htmlAudioElement);
  58218. }
  58219. break;
  58220. }
  58221. }
  58222. break;
  58223. default:
  58224. validParameter = false;
  58225. break;
  58226. }
  58227. if (!validParameter) {
  58228. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58229. }
  58230. else {
  58231. if (!codecSupportedFound) {
  58232. this._isReadyToPlay = true;
  58233. // Simulating a ready to play event to avoid breaking code path
  58234. if (this._readyToPlayCallback) {
  58235. window.setTimeout(function () {
  58236. if (_this._readyToPlayCallback) {
  58237. _this._readyToPlayCallback();
  58238. }
  58239. }, 1000);
  58240. }
  58241. }
  58242. }
  58243. }
  58244. catch (ex) {
  58245. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58246. this._scene.mainSoundTrack.RemoveSound(this);
  58247. }
  58248. }
  58249. }
  58250. else {
  58251. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58252. this._scene.mainSoundTrack.AddSound(this);
  58253. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58254. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58255. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58256. }
  58257. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58258. if (this._readyToPlayCallback) {
  58259. window.setTimeout(function () {
  58260. if (_this._readyToPlayCallback) {
  58261. _this._readyToPlayCallback();
  58262. }
  58263. }, 1000);
  58264. }
  58265. }
  58266. }
  58267. Sound.prototype.dispose = function () {
  58268. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58269. if (this.isPlaying) {
  58270. this.stop();
  58271. }
  58272. this._isReadyToPlay = false;
  58273. if (this.soundTrackId === -1) {
  58274. this._scene.mainSoundTrack.RemoveSound(this);
  58275. }
  58276. else {
  58277. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58278. }
  58279. if (this._soundGain) {
  58280. this._soundGain.disconnect();
  58281. this._soundGain = null;
  58282. }
  58283. if (this._soundPanner) {
  58284. this._soundPanner.disconnect();
  58285. this._soundPanner = null;
  58286. }
  58287. if (this._soundSource) {
  58288. this._soundSource.disconnect();
  58289. this._soundSource = null;
  58290. }
  58291. this._audioBuffer = null;
  58292. if (this._htmlAudioElement) {
  58293. this._htmlAudioElement.pause();
  58294. this._htmlAudioElement.src = "";
  58295. document.body.removeChild(this._htmlAudioElement);
  58296. }
  58297. if (this._connectedMesh && this._registerFunc) {
  58298. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58299. this._connectedMesh = null;
  58300. }
  58301. }
  58302. };
  58303. Sound.prototype.isReady = function () {
  58304. return this._isReadyToPlay;
  58305. };
  58306. Sound.prototype._soundLoaded = function (audioData) {
  58307. var _this = this;
  58308. if (!BABYLON.Engine.audioEngine.audioContext) {
  58309. return;
  58310. }
  58311. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58312. _this._audioBuffer = buffer;
  58313. _this._isReadyToPlay = true;
  58314. if (_this.autoplay) {
  58315. _this.play();
  58316. }
  58317. if (_this._readyToPlayCallback) {
  58318. _this._readyToPlayCallback();
  58319. }
  58320. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58321. };
  58322. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58323. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58324. this._audioBuffer = audioBuffer;
  58325. this._isReadyToPlay = true;
  58326. }
  58327. };
  58328. Sound.prototype.updateOptions = function (options) {
  58329. if (options) {
  58330. this.loop = options.loop || this.loop;
  58331. this.maxDistance = options.maxDistance || this.maxDistance;
  58332. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58333. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58334. this.refDistance = options.refDistance || this.refDistance;
  58335. this.distanceModel = options.distanceModel || this.distanceModel;
  58336. this._playbackRate = options.playbackRate || this._playbackRate;
  58337. this._updateSpatialParameters();
  58338. if (this.isPlaying) {
  58339. if (this._streaming) {
  58340. this._htmlAudioElement.playbackRate = this._playbackRate;
  58341. }
  58342. else {
  58343. if (this._soundSource) {
  58344. this._soundSource.playbackRate.value = this._playbackRate;
  58345. }
  58346. }
  58347. }
  58348. }
  58349. };
  58350. Sound.prototype._createSpatialParameters = function () {
  58351. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58352. if (this._scene.headphone) {
  58353. this._panningModel = "HRTF";
  58354. }
  58355. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58356. this._updateSpatialParameters();
  58357. this._soundPanner.connect(this._ouputAudioNode);
  58358. this._inputAudioNode = this._soundPanner;
  58359. }
  58360. };
  58361. Sound.prototype._updateSpatialParameters = function () {
  58362. if (this.spatialSound && this._soundPanner) {
  58363. if (this.useCustomAttenuation) {
  58364. // Tricks to disable in a way embedded Web Audio attenuation
  58365. this._soundPanner.distanceModel = "linear";
  58366. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58367. this._soundPanner.refDistance = 1;
  58368. this._soundPanner.rolloffFactor = 1;
  58369. this._soundPanner.panningModel = this._panningModel;
  58370. }
  58371. else {
  58372. this._soundPanner.distanceModel = this.distanceModel;
  58373. this._soundPanner.maxDistance = this.maxDistance;
  58374. this._soundPanner.refDistance = this.refDistance;
  58375. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58376. this._soundPanner.panningModel = this._panningModel;
  58377. }
  58378. }
  58379. };
  58380. Sound.prototype.switchPanningModelToHRTF = function () {
  58381. this._panningModel = "HRTF";
  58382. this._switchPanningModel();
  58383. };
  58384. Sound.prototype.switchPanningModelToEqualPower = function () {
  58385. this._panningModel = "equalpower";
  58386. this._switchPanningModel();
  58387. };
  58388. Sound.prototype._switchPanningModel = function () {
  58389. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58390. this._soundPanner.panningModel = this._panningModel;
  58391. }
  58392. };
  58393. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58394. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58395. if (this._isOutputConnected) {
  58396. this._ouputAudioNode.disconnect();
  58397. }
  58398. this._ouputAudioNode.connect(soundTrackAudioNode);
  58399. this._isOutputConnected = true;
  58400. }
  58401. };
  58402. /**
  58403. * Transform this sound into a directional source
  58404. * @param coneInnerAngle Size of the inner cone in degree
  58405. * @param coneOuterAngle Size of the outer cone in degree
  58406. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58407. */
  58408. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58409. if (coneOuterAngle < coneInnerAngle) {
  58410. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58411. return;
  58412. }
  58413. this._coneInnerAngle = coneInnerAngle;
  58414. this._coneOuterAngle = coneOuterAngle;
  58415. this._coneOuterGain = coneOuterGain;
  58416. this._isDirectional = true;
  58417. if (this.isPlaying && this.loop) {
  58418. this.stop();
  58419. this.play();
  58420. }
  58421. };
  58422. Sound.prototype.setPosition = function (newPosition) {
  58423. this._position = newPosition;
  58424. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58425. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58426. }
  58427. };
  58428. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58429. this._localDirection = newLocalDirection;
  58430. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58431. this._updateDirection();
  58432. }
  58433. };
  58434. Sound.prototype._updateDirection = function () {
  58435. if (!this._connectedMesh || !this._soundPanner) {
  58436. return;
  58437. }
  58438. var mat = this._connectedMesh.getWorldMatrix();
  58439. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58440. direction.normalize();
  58441. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58442. };
  58443. Sound.prototype.updateDistanceFromListener = function () {
  58444. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58445. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58446. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58447. }
  58448. };
  58449. Sound.prototype.setAttenuationFunction = function (callback) {
  58450. this._customAttenuationFunction = callback;
  58451. };
  58452. /**
  58453. * Play the sound
  58454. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58455. * @param offset (optional) Start the sound setting it at a specific time
  58456. */
  58457. Sound.prototype.play = function (time, offset) {
  58458. var _this = this;
  58459. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58460. try {
  58461. if (this._startOffset < 0) {
  58462. time = -this._startOffset;
  58463. this._startOffset = 0;
  58464. }
  58465. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58466. if (!this._soundSource || !this._streamingSource) {
  58467. if (this.spatialSound && this._soundPanner) {
  58468. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58469. if (this._isDirectional) {
  58470. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58471. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58472. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58473. if (this._connectedMesh) {
  58474. this._updateDirection();
  58475. }
  58476. else {
  58477. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58478. }
  58479. }
  58480. }
  58481. }
  58482. if (this._streaming) {
  58483. if (!this._streamingSource) {
  58484. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58485. this._htmlAudioElement.onended = function () { _this._onended(); };
  58486. this._htmlAudioElement.playbackRate = this._playbackRate;
  58487. }
  58488. this._streamingSource.disconnect();
  58489. this._streamingSource.connect(this._inputAudioNode);
  58490. this._htmlAudioElement.play();
  58491. }
  58492. else {
  58493. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58494. this._soundSource.buffer = this._audioBuffer;
  58495. this._soundSource.connect(this._inputAudioNode);
  58496. this._soundSource.loop = this.loop;
  58497. this._soundSource.playbackRate.value = this._playbackRate;
  58498. this._soundSource.onended = function () { _this._onended(); };
  58499. if (this._soundSource.buffer) {
  58500. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58501. }
  58502. }
  58503. this._startTime = startTime;
  58504. this.isPlaying = true;
  58505. this.isPaused = false;
  58506. }
  58507. catch (ex) {
  58508. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58509. }
  58510. }
  58511. };
  58512. Sound.prototype._onended = function () {
  58513. this.isPlaying = false;
  58514. if (this.onended) {
  58515. this.onended();
  58516. }
  58517. };
  58518. /**
  58519. * Stop the sound
  58520. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58521. */
  58522. Sound.prototype.stop = function (time) {
  58523. if (this.isPlaying) {
  58524. if (this._streaming) {
  58525. this._htmlAudioElement.pause();
  58526. // Test needed for Firefox or it will generate an Invalid State Error
  58527. if (this._htmlAudioElement.currentTime > 0) {
  58528. this._htmlAudioElement.currentTime = 0;
  58529. }
  58530. }
  58531. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58532. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58533. this._soundSource.stop(stopTime);
  58534. this._soundSource.onended = function () { };
  58535. if (!this.isPaused) {
  58536. this._startOffset = 0;
  58537. }
  58538. }
  58539. this.isPlaying = false;
  58540. }
  58541. };
  58542. Sound.prototype.pause = function () {
  58543. if (this.isPlaying) {
  58544. this.isPaused = true;
  58545. if (this._streaming) {
  58546. this._htmlAudioElement.pause();
  58547. }
  58548. else if (BABYLON.Engine.audioEngine.audioContext) {
  58549. this.stop(0);
  58550. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58551. }
  58552. }
  58553. };
  58554. Sound.prototype.setVolume = function (newVolume, time) {
  58555. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58556. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58557. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58558. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58559. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58560. }
  58561. else {
  58562. this._soundGain.gain.value = newVolume;
  58563. }
  58564. }
  58565. this._volume = newVolume;
  58566. };
  58567. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58568. this._playbackRate = newPlaybackRate;
  58569. if (this.isPlaying) {
  58570. if (this._streaming) {
  58571. this._htmlAudioElement.playbackRate = this._playbackRate;
  58572. }
  58573. else if (this._soundSource) {
  58574. this._soundSource.playbackRate.value = this._playbackRate;
  58575. }
  58576. }
  58577. };
  58578. Sound.prototype.getVolume = function () {
  58579. return this._volume;
  58580. };
  58581. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58582. var _this = this;
  58583. if (this._connectedMesh && this._registerFunc) {
  58584. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58585. this._registerFunc = null;
  58586. }
  58587. this._connectedMesh = meshToConnectTo;
  58588. if (!this.spatialSound) {
  58589. this.spatialSound = true;
  58590. this._createSpatialParameters();
  58591. if (this.isPlaying && this.loop) {
  58592. this.stop();
  58593. this.play();
  58594. }
  58595. }
  58596. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58597. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58598. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58599. };
  58600. Sound.prototype.detachFromMesh = function () {
  58601. if (this._connectedMesh && this._registerFunc) {
  58602. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58603. this._registerFunc = null;
  58604. this._connectedMesh = null;
  58605. }
  58606. };
  58607. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58608. if (!node.getBoundingInfo) {
  58609. return;
  58610. }
  58611. var mesh = node;
  58612. var boundingInfo = mesh.getBoundingInfo();
  58613. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58614. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58615. this._updateDirection();
  58616. }
  58617. };
  58618. Sound.prototype.clone = function () {
  58619. var _this = this;
  58620. if (!this._streaming) {
  58621. var setBufferAndRun = function () {
  58622. if (_this._isReadyToPlay) {
  58623. clonedSound._audioBuffer = _this.getAudioBuffer();
  58624. clonedSound._isReadyToPlay = true;
  58625. if (clonedSound.autoplay) {
  58626. clonedSound.play();
  58627. }
  58628. }
  58629. else {
  58630. window.setTimeout(setBufferAndRun, 300);
  58631. }
  58632. };
  58633. var currentOptions = {
  58634. autoplay: this.autoplay, loop: this.loop,
  58635. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58636. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58637. refDistance: this.refDistance, distanceModel: this.distanceModel
  58638. };
  58639. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58640. if (this.useCustomAttenuation) {
  58641. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58642. }
  58643. clonedSound.setPosition(this._position);
  58644. clonedSound.setPlaybackRate(this._playbackRate);
  58645. setBufferAndRun();
  58646. return clonedSound;
  58647. }
  58648. else {
  58649. return null;
  58650. }
  58651. };
  58652. Sound.prototype.getAudioBuffer = function () {
  58653. return this._audioBuffer;
  58654. };
  58655. Sound.prototype.serialize = function () {
  58656. var serializationObject = {
  58657. name: this.name,
  58658. url: this.name,
  58659. autoplay: this.autoplay,
  58660. loop: this.loop,
  58661. volume: this._volume,
  58662. spatialSound: this.spatialSound,
  58663. maxDistance: this.maxDistance,
  58664. rolloffFactor: this.rolloffFactor,
  58665. refDistance: this.refDistance,
  58666. distanceModel: this.distanceModel,
  58667. playbackRate: this._playbackRate,
  58668. panningModel: this._panningModel,
  58669. soundTrackId: this.soundTrackId
  58670. };
  58671. if (this.spatialSound) {
  58672. if (this._connectedMesh)
  58673. serializationObject.connectedMeshId = this._connectedMesh.id;
  58674. serializationObject.position = this._position.asArray();
  58675. serializationObject.refDistance = this.refDistance;
  58676. serializationObject.distanceModel = this.distanceModel;
  58677. serializationObject.isDirectional = this._isDirectional;
  58678. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58679. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58680. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58681. serializationObject.coneOuterGain = this._coneOuterGain;
  58682. }
  58683. return serializationObject;
  58684. };
  58685. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58686. var soundName = parsedSound.name;
  58687. var soundUrl;
  58688. if (parsedSound.url) {
  58689. soundUrl = rootUrl + parsedSound.url;
  58690. }
  58691. else {
  58692. soundUrl = rootUrl + soundName;
  58693. }
  58694. var options = {
  58695. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58696. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58697. rolloffFactor: parsedSound.rolloffFactor,
  58698. refDistance: parsedSound.refDistance,
  58699. distanceModel: parsedSound.distanceModel,
  58700. playbackRate: parsedSound.playbackRate
  58701. };
  58702. var newSound;
  58703. if (!sourceSound) {
  58704. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58705. scene._addPendingData(newSound);
  58706. }
  58707. else {
  58708. var setBufferAndRun = function () {
  58709. if (sourceSound._isReadyToPlay) {
  58710. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58711. newSound._isReadyToPlay = true;
  58712. if (newSound.autoplay) {
  58713. newSound.play();
  58714. }
  58715. }
  58716. else {
  58717. window.setTimeout(setBufferAndRun, 300);
  58718. }
  58719. };
  58720. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58721. setBufferAndRun();
  58722. }
  58723. if (parsedSound.position) {
  58724. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58725. newSound.setPosition(soundPosition);
  58726. }
  58727. if (parsedSound.isDirectional) {
  58728. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58729. if (parsedSound.localDirectionToMesh) {
  58730. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58731. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58732. }
  58733. }
  58734. if (parsedSound.connectedMeshId) {
  58735. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58736. if (connectedMesh) {
  58737. newSound.attachToMesh(connectedMesh);
  58738. }
  58739. }
  58740. return newSound;
  58741. };
  58742. return Sound;
  58743. }());
  58744. BABYLON.Sound = Sound;
  58745. })(BABYLON || (BABYLON = {}));
  58746. //# sourceMappingURL=babylon.sound.js.map
  58747. "use strict";
  58748. var BABYLON;
  58749. (function (BABYLON) {
  58750. var SoundTrack = /** @class */ (function () {
  58751. function SoundTrack(scene, options) {
  58752. this.id = -1;
  58753. this._isMainTrack = false;
  58754. this._isInitialized = false;
  58755. this._scene = scene;
  58756. this.soundCollection = new Array();
  58757. this._options = options;
  58758. if (!this._isMainTrack) {
  58759. this._scene.soundTracks.push(this);
  58760. this.id = this._scene.soundTracks.length - 1;
  58761. }
  58762. }
  58763. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58764. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58765. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58766. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58767. if (this._options) {
  58768. if (this._options.volume) {
  58769. this._outputAudioNode.gain.value = this._options.volume;
  58770. }
  58771. if (this._options.mainTrack) {
  58772. this._isMainTrack = this._options.mainTrack;
  58773. }
  58774. }
  58775. this._isInitialized = true;
  58776. }
  58777. };
  58778. SoundTrack.prototype.dispose = function () {
  58779. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58780. if (this._connectedAnalyser) {
  58781. this._connectedAnalyser.stopDebugCanvas();
  58782. }
  58783. while (this.soundCollection.length) {
  58784. this.soundCollection[0].dispose();
  58785. }
  58786. if (this._outputAudioNode) {
  58787. this._outputAudioNode.disconnect();
  58788. }
  58789. this._outputAudioNode = null;
  58790. }
  58791. };
  58792. SoundTrack.prototype.AddSound = function (sound) {
  58793. if (!this._isInitialized) {
  58794. this._initializeSoundTrackAudioGraph();
  58795. }
  58796. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58797. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58798. }
  58799. if (sound.soundTrackId) {
  58800. if (sound.soundTrackId === -1) {
  58801. this._scene.mainSoundTrack.RemoveSound(sound);
  58802. }
  58803. else {
  58804. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58805. }
  58806. }
  58807. this.soundCollection.push(sound);
  58808. sound.soundTrackId = this.id;
  58809. };
  58810. SoundTrack.prototype.RemoveSound = function (sound) {
  58811. var index = this.soundCollection.indexOf(sound);
  58812. if (index !== -1) {
  58813. this.soundCollection.splice(index, 1);
  58814. }
  58815. };
  58816. SoundTrack.prototype.setVolume = function (newVolume) {
  58817. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58818. this._outputAudioNode.gain.value = newVolume;
  58819. }
  58820. };
  58821. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58823. for (var i = 0; i < this.soundCollection.length; i++) {
  58824. this.soundCollection[i].switchPanningModelToHRTF();
  58825. }
  58826. }
  58827. };
  58828. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58829. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58830. for (var i = 0; i < this.soundCollection.length; i++) {
  58831. this.soundCollection[i].switchPanningModelToEqualPower();
  58832. }
  58833. }
  58834. };
  58835. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58836. if (this._connectedAnalyser) {
  58837. this._connectedAnalyser.stopDebugCanvas();
  58838. }
  58839. this._connectedAnalyser = analyser;
  58840. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58841. this._outputAudioNode.disconnect();
  58842. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58843. }
  58844. };
  58845. return SoundTrack;
  58846. }());
  58847. BABYLON.SoundTrack = SoundTrack;
  58848. })(BABYLON || (BABYLON = {}));
  58849. //# sourceMappingURL=babylon.soundtrack.js.map
  58850. "use strict";
  58851. var BABYLON;
  58852. (function (BABYLON) {
  58853. var Analyser = /** @class */ (function () {
  58854. function Analyser(scene) {
  58855. this.SMOOTHING = 0.75;
  58856. this.FFT_SIZE = 512;
  58857. this.BARGRAPHAMPLITUDE = 256;
  58858. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58859. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58860. this._scene = scene;
  58861. this._audioEngine = BABYLON.Engine.audioEngine;
  58862. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58863. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58864. this._webAudioAnalyser.minDecibels = -140;
  58865. this._webAudioAnalyser.maxDecibels = 0;
  58866. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58867. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58868. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58869. }
  58870. }
  58871. Analyser.prototype.getFrequencyBinCount = function () {
  58872. if (this._audioEngine.canUseWebAudio) {
  58873. return this._webAudioAnalyser.frequencyBinCount;
  58874. }
  58875. else {
  58876. return 0;
  58877. }
  58878. };
  58879. Analyser.prototype.getByteFrequencyData = function () {
  58880. if (this._audioEngine.canUseWebAudio) {
  58881. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58882. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58883. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58884. }
  58885. return this._byteFreqs;
  58886. };
  58887. Analyser.prototype.getByteTimeDomainData = function () {
  58888. if (this._audioEngine.canUseWebAudio) {
  58889. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58890. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58891. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58892. }
  58893. return this._byteTime;
  58894. };
  58895. Analyser.prototype.getFloatFrequencyData = function () {
  58896. if (this._audioEngine.canUseWebAudio) {
  58897. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58898. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58899. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58900. }
  58901. return this._floatFreqs;
  58902. };
  58903. Analyser.prototype.drawDebugCanvas = function () {
  58904. var _this = this;
  58905. if (this._audioEngine.canUseWebAudio) {
  58906. if (!this._debugCanvas) {
  58907. this._debugCanvas = document.createElement("canvas");
  58908. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58909. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58910. this._debugCanvas.style.position = "absolute";
  58911. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58912. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58913. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58914. document.body.appendChild(this._debugCanvas);
  58915. this._registerFunc = function () {
  58916. _this.drawDebugCanvas();
  58917. };
  58918. this._scene.registerBeforeRender(this._registerFunc);
  58919. }
  58920. if (this._registerFunc && this._debugCanvasContext) {
  58921. var workingArray = this.getByteFrequencyData();
  58922. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58923. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58924. // Draw the frequency domain chart.
  58925. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58926. var value = workingArray[i];
  58927. var percent = value / this.BARGRAPHAMPLITUDE;
  58928. var height = this.DEBUGCANVASSIZE.height * percent;
  58929. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58930. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58931. var hue = i / this.getFrequencyBinCount() * 360;
  58932. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58933. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58934. }
  58935. }
  58936. }
  58937. };
  58938. Analyser.prototype.stopDebugCanvas = function () {
  58939. if (this._debugCanvas) {
  58940. if (this._registerFunc) {
  58941. this._scene.unregisterBeforeRender(this._registerFunc);
  58942. this._registerFunc = null;
  58943. }
  58944. document.body.removeChild(this._debugCanvas);
  58945. this._debugCanvas = null;
  58946. this._debugCanvasContext = null;
  58947. }
  58948. };
  58949. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58950. if (this._audioEngine.canUseWebAudio) {
  58951. inputAudioNode.connect(this._webAudioAnalyser);
  58952. this._webAudioAnalyser.connect(outputAudioNode);
  58953. }
  58954. };
  58955. Analyser.prototype.dispose = function () {
  58956. if (this._audioEngine.canUseWebAudio) {
  58957. this._webAudioAnalyser.disconnect();
  58958. }
  58959. };
  58960. return Analyser;
  58961. }());
  58962. BABYLON.Analyser = Analyser;
  58963. })(BABYLON || (BABYLON = {}));
  58964. //# sourceMappingURL=babylon.analyser.js.map
  58965. "use strict";
  58966. var BABYLON;
  58967. (function (BABYLON) {
  58968. var CubeTexture = /** @class */ (function (_super) {
  58969. __extends(CubeTexture, _super);
  58970. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58971. if (extensions === void 0) { extensions = null; }
  58972. if (noMipmap === void 0) { noMipmap = false; }
  58973. if (files === void 0) { files = null; }
  58974. if (onLoad === void 0) { onLoad = null; }
  58975. if (onError === void 0) { onError = null; }
  58976. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58977. if (prefiltered === void 0) { prefiltered = false; }
  58978. if (forcedExtension === void 0) { forcedExtension = null; }
  58979. var _this = _super.call(this, scene) || this;
  58980. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58981. /**
  58982. * Gets or sets the center of the bounding box associated with the cube texture
  58983. * It must define where the camera used to render the texture was set
  58984. */
  58985. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58986. _this.name = rootUrl;
  58987. _this.url = rootUrl;
  58988. _this._noMipmap = noMipmap;
  58989. _this.hasAlpha = false;
  58990. _this._format = format;
  58991. _this._prefiltered = prefiltered;
  58992. _this.isCube = true;
  58993. _this._textureMatrix = BABYLON.Matrix.Identity();
  58994. if (prefiltered) {
  58995. _this.gammaSpace = false;
  58996. }
  58997. if (!rootUrl && !files) {
  58998. return _this;
  58999. }
  59000. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  59001. var lastDot = rootUrl.lastIndexOf(".");
  59002. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  59003. var isDDS = (extension === ".dds");
  59004. if (!files) {
  59005. if (!isDDS && !extensions) {
  59006. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  59007. }
  59008. files = [];
  59009. if (extensions) {
  59010. for (var index = 0; index < extensions.length; index++) {
  59011. files.push(rootUrl + extensions[index]);
  59012. }
  59013. }
  59014. }
  59015. _this._files = files;
  59016. if (!_this._texture) {
  59017. if (!scene.useDelayedTextureLoading) {
  59018. if (prefiltered) {
  59019. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  59020. }
  59021. else {
  59022. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  59023. }
  59024. }
  59025. else {
  59026. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59027. }
  59028. }
  59029. else if (onLoad) {
  59030. if (_this._texture.isReady) {
  59031. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  59032. }
  59033. else {
  59034. _this._texture.onLoadedObservable.add(onLoad);
  59035. }
  59036. }
  59037. return _this;
  59038. }
  59039. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  59040. get: function () {
  59041. return this._boundingBoxSize;
  59042. },
  59043. /**
  59044. * Gets or sets the size of the bounding box associated with the cube texture
  59045. * When defined, the cubemap will switch to local mode
  59046. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59047. * @example https://www.babylonjs-playground.com/#RNASML
  59048. */
  59049. set: function (value) {
  59050. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59051. return;
  59052. }
  59053. this._boundingBoxSize = value;
  59054. var scene = this.getScene();
  59055. if (scene) {
  59056. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59057. }
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59063. var rootUrlKey = "";
  59064. files.forEach(function (url) { return rootUrlKey += url; });
  59065. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59066. };
  59067. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59068. if (forcedExtension === void 0) { forcedExtension = null; }
  59069. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59070. };
  59071. // Methods
  59072. CubeTexture.prototype.delayLoad = function () {
  59073. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59074. return;
  59075. }
  59076. var scene = this.getScene();
  59077. if (!scene) {
  59078. return;
  59079. }
  59080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59081. this._texture = this._getFromCache(this.url, this._noMipmap);
  59082. if (!this._texture) {
  59083. if (this._prefiltered) {
  59084. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59085. }
  59086. else {
  59087. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59088. }
  59089. }
  59090. };
  59091. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59092. return this._textureMatrix;
  59093. };
  59094. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59095. this._textureMatrix = value;
  59096. };
  59097. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59098. var texture = BABYLON.SerializationHelper.Parse(function () {
  59099. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59100. }, parsedTexture, scene);
  59101. // Local Cubemaps
  59102. if (parsedTexture.boundingBoxPosition) {
  59103. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59104. }
  59105. if (parsedTexture.boundingBoxSize) {
  59106. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59107. }
  59108. // Animations
  59109. if (parsedTexture.animations) {
  59110. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59111. var parsedAnimation = parsedTexture.animations[animationIndex];
  59112. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59113. }
  59114. }
  59115. return texture;
  59116. };
  59117. CubeTexture.prototype.clone = function () {
  59118. var _this = this;
  59119. return BABYLON.SerializationHelper.Clone(function () {
  59120. var scene = _this.getScene();
  59121. if (!scene) {
  59122. return _this;
  59123. }
  59124. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59125. }, this);
  59126. };
  59127. return CubeTexture;
  59128. }(BABYLON.BaseTexture));
  59129. BABYLON.CubeTexture = CubeTexture;
  59130. })(BABYLON || (BABYLON = {}));
  59131. //# sourceMappingURL=babylon.cubeTexture.js.map
  59132. "use strict";
  59133. var BABYLON;
  59134. (function (BABYLON) {
  59135. var RenderTargetTexture = /** @class */ (function (_super) {
  59136. __extends(RenderTargetTexture, _super);
  59137. /**
  59138. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59139. * or used a shadow, depth texture...
  59140. * @param name The friendly name of the texture
  59141. * @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)
  59142. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59143. * @param generateMipMaps True if mip maps need to be generated after render.
  59144. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59145. * @param type The type of the buffer in the RTT (int, half float, float...)
  59146. * @param isCube True if a cube texture needs to be created
  59147. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59148. * @param generateDepthBuffer True to generate a depth buffer
  59149. * @param generateStencilBuffer True to generate a stencil buffer
  59150. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59151. */
  59152. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59153. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59154. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59155. if (isCube === void 0) { isCube = false; }
  59156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59157. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59158. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59159. if (isMulti === void 0) { isMulti = false; }
  59160. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59161. _this.isCube = isCube;
  59162. /**
  59163. * Use this list to define the list of mesh you want to render.
  59164. */
  59165. _this.renderList = new Array();
  59166. _this.renderParticles = true;
  59167. _this.renderSprites = false;
  59168. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59169. _this.ignoreCameraViewport = false;
  59170. // Events
  59171. /**
  59172. * An event triggered when the texture is unbind.
  59173. * @type {BABYLON.Observable}
  59174. */
  59175. _this.onBeforeBindObservable = new BABYLON.Observable();
  59176. /**
  59177. * An event triggered when the texture is unbind.
  59178. * @type {BABYLON.Observable}
  59179. */
  59180. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59181. /**
  59182. * An event triggered before rendering the texture
  59183. * @type {BABYLON.Observable}
  59184. */
  59185. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59186. /**
  59187. * An event triggered after rendering the texture
  59188. * @type {BABYLON.Observable}
  59189. */
  59190. _this.onAfterRenderObservable = new BABYLON.Observable();
  59191. /**
  59192. * An event triggered after the texture clear
  59193. * @type {BABYLON.Observable}
  59194. */
  59195. _this.onClearObservable = new BABYLON.Observable();
  59196. _this._currentRefreshId = -1;
  59197. _this._refreshRate = 1;
  59198. _this._samples = 1;
  59199. /**
  59200. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59201. * It must define where the camera used to render the texture is set
  59202. */
  59203. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59204. scene = _this.getScene();
  59205. if (!scene) {
  59206. return _this;
  59207. }
  59208. _this._engine = scene.getEngine();
  59209. _this.name = name;
  59210. _this.isRenderTarget = true;
  59211. _this._initialSizeParameter = size;
  59212. _this._processSizeParameter(size);
  59213. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59214. });
  59215. _this._generateMipMaps = generateMipMaps ? true : false;
  59216. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59217. // Rendering groups
  59218. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59219. if (isMulti) {
  59220. return _this;
  59221. }
  59222. _this._renderTargetOptions = {
  59223. generateMipMaps: generateMipMaps,
  59224. type: type,
  59225. samplingMode: samplingMode,
  59226. generateDepthBuffer: generateDepthBuffer,
  59227. generateStencilBuffer: generateStencilBuffer
  59228. };
  59229. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59230. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59231. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59232. }
  59233. if (isCube) {
  59234. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59235. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59236. _this._textureMatrix = BABYLON.Matrix.Identity();
  59237. }
  59238. else {
  59239. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59240. }
  59241. return _this;
  59242. }
  59243. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59244. get: function () {
  59245. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59246. },
  59247. enumerable: true,
  59248. configurable: true
  59249. });
  59250. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59251. get: function () {
  59252. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59253. },
  59254. enumerable: true,
  59255. configurable: true
  59256. });
  59257. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59258. get: function () {
  59259. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59260. },
  59261. enumerable: true,
  59262. configurable: true
  59263. });
  59264. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59265. set: function (callback) {
  59266. if (this._onAfterUnbindObserver) {
  59267. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59268. }
  59269. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59270. },
  59271. enumerable: true,
  59272. configurable: true
  59273. });
  59274. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59275. set: function (callback) {
  59276. if (this._onBeforeRenderObserver) {
  59277. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59278. }
  59279. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59280. },
  59281. enumerable: true,
  59282. configurable: true
  59283. });
  59284. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59285. set: function (callback) {
  59286. if (this._onAfterRenderObserver) {
  59287. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59288. }
  59289. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59290. },
  59291. enumerable: true,
  59292. configurable: true
  59293. });
  59294. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59295. set: function (callback) {
  59296. if (this._onClearObserver) {
  59297. this.onClearObservable.remove(this._onClearObserver);
  59298. }
  59299. this._onClearObserver = this.onClearObservable.add(callback);
  59300. },
  59301. enumerable: true,
  59302. configurable: true
  59303. });
  59304. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59305. get: function () {
  59306. return this._renderTargetOptions;
  59307. },
  59308. enumerable: true,
  59309. configurable: true
  59310. });
  59311. RenderTargetTexture.prototype._onRatioRescale = function () {
  59312. if (this._sizeRatio) {
  59313. this.resize(this._initialSizeParameter);
  59314. }
  59315. };
  59316. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59317. get: function () {
  59318. return this._boundingBoxSize;
  59319. },
  59320. /**
  59321. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59322. * When defined, the cubemap will switch to local mode
  59323. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59324. * @example https://www.babylonjs-playground.com/#RNASML
  59325. */
  59326. set: function (value) {
  59327. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59328. return;
  59329. }
  59330. this._boundingBoxSize = value;
  59331. var scene = this.getScene();
  59332. if (scene) {
  59333. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59334. }
  59335. },
  59336. enumerable: true,
  59337. configurable: true
  59338. });
  59339. /**
  59340. * Creates a depth stencil texture.
  59341. * This is only available in WebGL 2 or with the depth texture extension available.
  59342. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59343. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59344. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59345. */
  59346. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59347. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59348. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59349. if (generateStencil === void 0) { generateStencil = false; }
  59350. if (!this.getScene()) {
  59351. return;
  59352. }
  59353. var engine = this.getScene().getEngine();
  59354. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59355. bilinearFiltering: bilinearFiltering,
  59356. comparisonFunction: comparisonFunction,
  59357. generateStencil: generateStencil,
  59358. isCube: this.isCube
  59359. });
  59360. engine.setFrameBufferDepthStencilTexture(this);
  59361. };
  59362. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59363. if (size.ratio) {
  59364. this._sizeRatio = size.ratio;
  59365. this._size = {
  59366. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59367. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59368. };
  59369. }
  59370. else {
  59371. this._size = size;
  59372. }
  59373. };
  59374. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59375. get: function () {
  59376. return this._samples;
  59377. },
  59378. set: function (value) {
  59379. if (this._samples === value) {
  59380. return;
  59381. }
  59382. var scene = this.getScene();
  59383. if (!scene) {
  59384. return;
  59385. }
  59386. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59387. },
  59388. enumerable: true,
  59389. configurable: true
  59390. });
  59391. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59392. this._currentRefreshId = -1;
  59393. };
  59394. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59395. get: function () {
  59396. return this._refreshRate;
  59397. },
  59398. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59399. set: function (value) {
  59400. this._refreshRate = value;
  59401. this.resetRefreshCounter();
  59402. },
  59403. enumerable: true,
  59404. configurable: true
  59405. });
  59406. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59407. if (!this._postProcessManager) {
  59408. var scene = this.getScene();
  59409. if (!scene) {
  59410. return;
  59411. }
  59412. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59413. this._postProcesses = new Array();
  59414. }
  59415. this._postProcesses.push(postProcess);
  59416. this._postProcesses[0].autoClear = false;
  59417. };
  59418. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59419. if (!this._postProcesses) {
  59420. return;
  59421. }
  59422. if (dispose) {
  59423. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59424. var postProcess = _a[_i];
  59425. postProcess.dispose();
  59426. }
  59427. }
  59428. this._postProcesses = [];
  59429. };
  59430. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59431. if (!this._postProcesses) {
  59432. return;
  59433. }
  59434. var index = this._postProcesses.indexOf(postProcess);
  59435. if (index === -1) {
  59436. return;
  59437. }
  59438. this._postProcesses.splice(index, 1);
  59439. if (this._postProcesses.length > 0) {
  59440. this._postProcesses[0].autoClear = false;
  59441. }
  59442. };
  59443. RenderTargetTexture.prototype._shouldRender = function () {
  59444. if (this._currentRefreshId === -1) {
  59445. this._currentRefreshId = 1;
  59446. return true;
  59447. }
  59448. if (this.refreshRate === this._currentRefreshId) {
  59449. this._currentRefreshId = 1;
  59450. return true;
  59451. }
  59452. this._currentRefreshId++;
  59453. return false;
  59454. };
  59455. RenderTargetTexture.prototype.getRenderSize = function () {
  59456. if (this._size.width) {
  59457. return this._size.width;
  59458. }
  59459. return this._size;
  59460. };
  59461. RenderTargetTexture.prototype.getRenderWidth = function () {
  59462. if (this._size.width) {
  59463. return this._size.width;
  59464. }
  59465. return this._size;
  59466. };
  59467. RenderTargetTexture.prototype.getRenderHeight = function () {
  59468. if (this._size.width) {
  59469. return this._size.height;
  59470. }
  59471. return this._size;
  59472. };
  59473. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59474. get: function () {
  59475. return true;
  59476. },
  59477. enumerable: true,
  59478. configurable: true
  59479. });
  59480. RenderTargetTexture.prototype.scale = function (ratio) {
  59481. var newSize = this.getRenderSize() * ratio;
  59482. this.resize(newSize);
  59483. };
  59484. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59485. if (this.isCube) {
  59486. return this._textureMatrix;
  59487. }
  59488. return _super.prototype.getReflectionTextureMatrix.call(this);
  59489. };
  59490. RenderTargetTexture.prototype.resize = function (size) {
  59491. this.releaseInternalTexture();
  59492. var scene = this.getScene();
  59493. if (!scene) {
  59494. return;
  59495. }
  59496. this._processSizeParameter(size);
  59497. if (this.isCube) {
  59498. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59499. }
  59500. else {
  59501. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59502. }
  59503. };
  59504. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59505. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59506. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59507. var scene = this.getScene();
  59508. if (!scene) {
  59509. return;
  59510. }
  59511. var engine = scene.getEngine();
  59512. if (this.useCameraPostProcesses !== undefined) {
  59513. useCameraPostProcess = this.useCameraPostProcesses;
  59514. }
  59515. if (this._waitingRenderList) {
  59516. this.renderList = [];
  59517. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59518. var id = this._waitingRenderList[index];
  59519. var mesh_1 = scene.getMeshByID(id);
  59520. if (mesh_1) {
  59521. this.renderList.push(mesh_1);
  59522. }
  59523. }
  59524. delete this._waitingRenderList;
  59525. }
  59526. // Is predicate defined?
  59527. if (this.renderListPredicate) {
  59528. if (this.renderList) {
  59529. this.renderList.splice(0); // Clear previous renderList
  59530. }
  59531. else {
  59532. this.renderList = [];
  59533. }
  59534. var scene = this.getScene();
  59535. if (!scene) {
  59536. return;
  59537. }
  59538. var sceneMeshes = scene.meshes;
  59539. for (var index = 0; index < sceneMeshes.length; index++) {
  59540. var mesh = sceneMeshes[index];
  59541. if (this.renderListPredicate(mesh)) {
  59542. this.renderList.push(mesh);
  59543. }
  59544. }
  59545. }
  59546. this.onBeforeBindObservable.notifyObservers(this);
  59547. // Set custom projection.
  59548. // Needs to be before binding to prevent changing the aspect ratio.
  59549. var camera;
  59550. if (this.activeCamera) {
  59551. camera = this.activeCamera;
  59552. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59553. if (this.activeCamera !== scene.activeCamera) {
  59554. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59555. }
  59556. }
  59557. else {
  59558. camera = scene.activeCamera;
  59559. if (camera) {
  59560. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59561. }
  59562. }
  59563. // Prepare renderingManager
  59564. this._renderingManager.reset();
  59565. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59566. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59567. var sceneRenderId = scene.getRenderId();
  59568. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59569. var mesh = currentRenderList[meshIndex];
  59570. if (mesh) {
  59571. if (!mesh.isReady(this.refreshRate === 0)) {
  59572. this.resetRefreshCounter();
  59573. continue;
  59574. }
  59575. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59576. var isMasked = void 0;
  59577. if (!this.renderList && camera) {
  59578. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59579. }
  59580. else {
  59581. isMasked = false;
  59582. }
  59583. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59584. mesh._activate(sceneRenderId);
  59585. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59586. var subMesh = mesh.subMeshes[subIndex];
  59587. scene._activeIndices.addCount(subMesh.indexCount, false);
  59588. this._renderingManager.dispatch(subMesh, mesh);
  59589. }
  59590. }
  59591. }
  59592. }
  59593. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59594. var particleSystem = scene.particleSystems[particleIndex];
  59595. var emitter = particleSystem.emitter;
  59596. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59597. continue;
  59598. }
  59599. if (currentRenderList.indexOf(emitter) >= 0) {
  59600. this._renderingManager.dispatchParticles(particleSystem);
  59601. }
  59602. }
  59603. if (this.isCube) {
  59604. for (var face = 0; face < 6; face++) {
  59605. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59606. scene.incrementRenderId();
  59607. scene.resetCachedMaterial();
  59608. }
  59609. }
  59610. else {
  59611. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59612. }
  59613. this.onAfterUnbindObservable.notifyObservers(this);
  59614. if (scene.activeCamera) {
  59615. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59616. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59617. }
  59618. engine.setViewport(scene.activeCamera.viewport);
  59619. }
  59620. scene.resetCachedMaterial();
  59621. };
  59622. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59623. var minimum = 128;
  59624. var x = renderDimension * scale;
  59625. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59626. // Ensure we don't exceed the render dimension (while staying POT)
  59627. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59628. };
  59629. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59630. var _this = this;
  59631. if (!this._texture) {
  59632. return;
  59633. }
  59634. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59635. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59636. });
  59637. };
  59638. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59639. var scene = this.getScene();
  59640. if (!scene) {
  59641. return;
  59642. }
  59643. var engine = scene.getEngine();
  59644. if (!this._texture) {
  59645. return;
  59646. }
  59647. // Bind
  59648. if (this._postProcessManager) {
  59649. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59650. }
  59651. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59652. if (this._texture) {
  59653. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59654. }
  59655. }
  59656. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59657. // Clear
  59658. if (this.onClearObservable.hasObservers()) {
  59659. this.onClearObservable.notifyObservers(engine);
  59660. }
  59661. else {
  59662. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59663. }
  59664. if (!this._doNotChangeAspectRatio) {
  59665. scene.updateTransformMatrix(true);
  59666. }
  59667. // Render
  59668. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59669. if (this._postProcessManager) {
  59670. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59671. }
  59672. else if (useCameraPostProcess) {
  59673. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59674. }
  59675. if (!this._doNotChangeAspectRatio) {
  59676. scene.updateTransformMatrix(true);
  59677. }
  59678. // Dump ?
  59679. if (dumpForDebug) {
  59680. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59681. }
  59682. // Unbind
  59683. if (!this.isCube || faceIndex === 5) {
  59684. if (this.isCube) {
  59685. if (faceIndex === 5) {
  59686. engine.generateMipMapsForCubemap(this._texture);
  59687. }
  59688. }
  59689. this.unbindFrameBuffer(engine, faceIndex);
  59690. }
  59691. else {
  59692. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59693. }
  59694. };
  59695. /**
  59696. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59697. * This allowed control for front to back rendering or reversly depending of the special needs.
  59698. *
  59699. * @param renderingGroupId The rendering group id corresponding to its index
  59700. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59701. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59702. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59703. */
  59704. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59705. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59706. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59707. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59708. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59709. };
  59710. /**
  59711. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59712. *
  59713. * @param renderingGroupId The rendering group id corresponding to its index
  59714. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59715. */
  59716. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59717. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59718. };
  59719. RenderTargetTexture.prototype.clone = function () {
  59720. var textureSize = this.getSize();
  59721. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59722. // Base texture
  59723. newTexture.hasAlpha = this.hasAlpha;
  59724. newTexture.level = this.level;
  59725. // RenderTarget Texture
  59726. newTexture.coordinatesMode = this.coordinatesMode;
  59727. if (this.renderList) {
  59728. newTexture.renderList = this.renderList.slice(0);
  59729. }
  59730. return newTexture;
  59731. };
  59732. RenderTargetTexture.prototype.serialize = function () {
  59733. if (!this.name) {
  59734. return null;
  59735. }
  59736. var serializationObject = _super.prototype.serialize.call(this);
  59737. serializationObject.renderTargetSize = this.getRenderSize();
  59738. serializationObject.renderList = [];
  59739. if (this.renderList) {
  59740. for (var index = 0; index < this.renderList.length; index++) {
  59741. serializationObject.renderList.push(this.renderList[index].id);
  59742. }
  59743. }
  59744. return serializationObject;
  59745. };
  59746. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59747. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59748. var objBuffer = this.getInternalTexture();
  59749. var scene = this.getScene();
  59750. if (objBuffer && scene) {
  59751. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59752. }
  59753. };
  59754. RenderTargetTexture.prototype.dispose = function () {
  59755. if (this._postProcessManager) {
  59756. this._postProcessManager.dispose();
  59757. this._postProcessManager = null;
  59758. }
  59759. this.clearPostProcesses(true);
  59760. if (this._resizeObserver) {
  59761. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59762. this._resizeObserver = null;
  59763. }
  59764. this.renderList = null;
  59765. // Remove from custom render targets
  59766. var scene = this.getScene();
  59767. if (!scene) {
  59768. return;
  59769. }
  59770. var index = scene.customRenderTargets.indexOf(this);
  59771. if (index >= 0) {
  59772. scene.customRenderTargets.splice(index, 1);
  59773. }
  59774. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59775. var camera = _a[_i];
  59776. index = camera.customRenderTargets.indexOf(this);
  59777. if (index >= 0) {
  59778. camera.customRenderTargets.splice(index, 1);
  59779. }
  59780. }
  59781. _super.prototype.dispose.call(this);
  59782. };
  59783. RenderTargetTexture.prototype._rebuild = function () {
  59784. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59785. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59786. }
  59787. if (this._postProcessManager) {
  59788. this._postProcessManager._rebuild();
  59789. }
  59790. };
  59791. /**
  59792. * Clear the info related to rendering groups preventing retention point in material dispose.
  59793. */
  59794. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59795. if (this._renderingManager) {
  59796. this._renderingManager.freeRenderingGroups();
  59797. }
  59798. };
  59799. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59800. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59801. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59802. return RenderTargetTexture;
  59803. }(BABYLON.Texture));
  59804. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59805. })(BABYLON || (BABYLON = {}));
  59806. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59807. "use strict";
  59808. var BABYLON;
  59809. (function (BABYLON) {
  59810. ;
  59811. var MultiRenderTarget = /** @class */ (function (_super) {
  59812. __extends(MultiRenderTarget, _super);
  59813. function MultiRenderTarget(name, size, count, scene, options) {
  59814. var _this = this;
  59815. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59816. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59817. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59818. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59819. _this._engine = scene.getEngine();
  59820. if (!_this.isSupported) {
  59821. _this.dispose();
  59822. return;
  59823. }
  59824. var types = [];
  59825. var samplingModes = [];
  59826. for (var i = 0; i < count; i++) {
  59827. if (options && options.types && options.types[i] !== undefined) {
  59828. types.push(options.types[i]);
  59829. }
  59830. else {
  59831. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59832. }
  59833. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59834. samplingModes.push(options.samplingModes[i]);
  59835. }
  59836. else {
  59837. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59838. }
  59839. }
  59840. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59841. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59842. _this._size = size;
  59843. _this._multiRenderTargetOptions = {
  59844. samplingModes: samplingModes,
  59845. generateMipMaps: generateMipMaps,
  59846. generateDepthBuffer: generateDepthBuffer,
  59847. generateStencilBuffer: generateStencilBuffer,
  59848. generateDepthTexture: generateDepthTexture,
  59849. types: types,
  59850. textureCount: count
  59851. };
  59852. _this._createInternalTextures();
  59853. _this._createTextures();
  59854. return _this;
  59855. }
  59856. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59857. get: function () {
  59858. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59859. },
  59860. enumerable: true,
  59861. configurable: true
  59862. });
  59863. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59864. get: function () {
  59865. return this._textures;
  59866. },
  59867. enumerable: true,
  59868. configurable: true
  59869. });
  59870. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59871. get: function () {
  59872. return this._textures[this._textures.length - 1];
  59873. },
  59874. enumerable: true,
  59875. configurable: true
  59876. });
  59877. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59878. set: function (wrap) {
  59879. if (this._textures) {
  59880. for (var i = 0; i < this._textures.length; i++) {
  59881. this._textures[i].wrapU = wrap;
  59882. }
  59883. }
  59884. },
  59885. enumerable: true,
  59886. configurable: true
  59887. });
  59888. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59889. set: function (wrap) {
  59890. if (this._textures) {
  59891. for (var i = 0; i < this._textures.length; i++) {
  59892. this._textures[i].wrapV = wrap;
  59893. }
  59894. }
  59895. },
  59896. enumerable: true,
  59897. configurable: true
  59898. });
  59899. MultiRenderTarget.prototype._rebuild = function () {
  59900. this.releaseInternalTextures();
  59901. this._createInternalTextures();
  59902. for (var i = 0; i < this._internalTextures.length; i++) {
  59903. var texture = this._textures[i];
  59904. texture._texture = this._internalTextures[i];
  59905. }
  59906. // Keeps references to frame buffer and stencil/depth buffer
  59907. this._texture = this._internalTextures[0];
  59908. };
  59909. MultiRenderTarget.prototype._createInternalTextures = function () {
  59910. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59911. };
  59912. MultiRenderTarget.prototype._createTextures = function () {
  59913. this._textures = [];
  59914. for (var i = 0; i < this._internalTextures.length; i++) {
  59915. var texture = new BABYLON.Texture(null, this.getScene());
  59916. texture._texture = this._internalTextures[i];
  59917. this._textures.push(texture);
  59918. }
  59919. // Keeps references to frame buffer and stencil/depth buffer
  59920. this._texture = this._internalTextures[0];
  59921. };
  59922. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59923. get: function () {
  59924. return this._samples;
  59925. },
  59926. set: function (value) {
  59927. if (this._samples === value) {
  59928. return;
  59929. }
  59930. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59931. },
  59932. enumerable: true,
  59933. configurable: true
  59934. });
  59935. MultiRenderTarget.prototype.resize = function (size) {
  59936. this.releaseInternalTextures();
  59937. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59938. this._createInternalTextures();
  59939. };
  59940. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59941. var _this = this;
  59942. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59943. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59944. });
  59945. };
  59946. MultiRenderTarget.prototype.dispose = function () {
  59947. this.releaseInternalTextures();
  59948. _super.prototype.dispose.call(this);
  59949. };
  59950. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59951. if (!this._internalTextures) {
  59952. return;
  59953. }
  59954. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59955. if (this._internalTextures[i] !== undefined) {
  59956. this._internalTextures[i].dispose();
  59957. this._internalTextures.splice(i, 1);
  59958. }
  59959. }
  59960. };
  59961. return MultiRenderTarget;
  59962. }(BABYLON.RenderTargetTexture));
  59963. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59964. })(BABYLON || (BABYLON = {}));
  59965. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59966. "use strict";
  59967. var BABYLON;
  59968. (function (BABYLON) {
  59969. var MirrorTexture = /** @class */ (function (_super) {
  59970. __extends(MirrorTexture, _super);
  59971. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59972. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59974. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59975. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59976. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59977. _this._transformMatrix = BABYLON.Matrix.Zero();
  59978. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59979. _this._adaptiveBlurKernel = 0;
  59980. _this._blurKernelX = 0;
  59981. _this._blurKernelY = 0;
  59982. _this._blurRatio = 1.0;
  59983. _this.ignoreCameraViewport = true;
  59984. _this.onBeforeRenderObservable.add(function () {
  59985. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59986. _this._savedViewMatrix = scene.getViewMatrix();
  59987. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59988. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59989. scene.clipPlane = _this.mirrorPlane;
  59990. scene.getEngine().cullBackFaces = false;
  59991. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59992. });
  59993. _this.onAfterRenderObservable.add(function () {
  59994. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59995. scene.getEngine().cullBackFaces = true;
  59996. scene._mirroredCameraPosition = null;
  59997. delete scene.clipPlane;
  59998. });
  59999. return _this;
  60000. }
  60001. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  60002. get: function () {
  60003. return this._blurRatio;
  60004. },
  60005. set: function (value) {
  60006. if (this._blurRatio === value) {
  60007. return;
  60008. }
  60009. this._blurRatio = value;
  60010. this._preparePostProcesses();
  60011. },
  60012. enumerable: true,
  60013. configurable: true
  60014. });
  60015. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  60016. set: function (value) {
  60017. this._adaptiveBlurKernel = value;
  60018. this._autoComputeBlurKernel();
  60019. },
  60020. enumerable: true,
  60021. configurable: true
  60022. });
  60023. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  60024. set: function (value) {
  60025. this.blurKernelX = value;
  60026. this.blurKernelY = value;
  60027. },
  60028. enumerable: true,
  60029. configurable: true
  60030. });
  60031. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  60032. get: function () {
  60033. return this._blurKernelX;
  60034. },
  60035. set: function (value) {
  60036. if (this._blurKernelX === value) {
  60037. return;
  60038. }
  60039. this._blurKernelX = value;
  60040. this._preparePostProcesses();
  60041. },
  60042. enumerable: true,
  60043. configurable: true
  60044. });
  60045. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  60046. get: function () {
  60047. return this._blurKernelY;
  60048. },
  60049. set: function (value) {
  60050. if (this._blurKernelY === value) {
  60051. return;
  60052. }
  60053. this._blurKernelY = value;
  60054. this._preparePostProcesses();
  60055. },
  60056. enumerable: true,
  60057. configurable: true
  60058. });
  60059. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60060. var engine = this.getScene().getEngine();
  60061. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60062. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60063. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60064. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60065. };
  60066. MirrorTexture.prototype._onRatioRescale = function () {
  60067. if (this._sizeRatio) {
  60068. this.resize(this._initialSizeParameter);
  60069. if (!this._adaptiveBlurKernel) {
  60070. this._preparePostProcesses();
  60071. }
  60072. }
  60073. if (this._adaptiveBlurKernel) {
  60074. this._autoComputeBlurKernel();
  60075. }
  60076. };
  60077. MirrorTexture.prototype._preparePostProcesses = function () {
  60078. this.clearPostProcesses(true);
  60079. if (this._blurKernelX && this._blurKernelY) {
  60080. var engine = this.getScene().getEngine();
  60081. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60082. 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);
  60083. this._blurX.autoClear = false;
  60084. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60085. this._blurX.inputTexture = this._texture;
  60086. }
  60087. else {
  60088. this._blurX.alwaysForcePOT = true;
  60089. }
  60090. 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);
  60091. this._blurY.autoClear = false;
  60092. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60093. this.addPostProcess(this._blurX);
  60094. this.addPostProcess(this._blurY);
  60095. }
  60096. else {
  60097. if (this._blurY) {
  60098. this.removePostProcess(this._blurY);
  60099. this._blurY.dispose();
  60100. this._blurY = null;
  60101. }
  60102. if (this._blurX) {
  60103. this.removePostProcess(this._blurX);
  60104. this._blurX.dispose();
  60105. this._blurX = null;
  60106. }
  60107. }
  60108. };
  60109. MirrorTexture.prototype.clone = function () {
  60110. var scene = this.getScene();
  60111. if (!scene) {
  60112. return this;
  60113. }
  60114. var textureSize = this.getSize();
  60115. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60116. // Base texture
  60117. newTexture.hasAlpha = this.hasAlpha;
  60118. newTexture.level = this.level;
  60119. // Mirror Texture
  60120. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60121. if (this.renderList) {
  60122. newTexture.renderList = this.renderList.slice(0);
  60123. }
  60124. return newTexture;
  60125. };
  60126. MirrorTexture.prototype.serialize = function () {
  60127. if (!this.name) {
  60128. return null;
  60129. }
  60130. var serializationObject = _super.prototype.serialize.call(this);
  60131. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60132. return serializationObject;
  60133. };
  60134. return MirrorTexture;
  60135. }(BABYLON.RenderTargetTexture));
  60136. BABYLON.MirrorTexture = MirrorTexture;
  60137. })(BABYLON || (BABYLON = {}));
  60138. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60139. "use strict";
  60140. var BABYLON;
  60141. (function (BABYLON) {
  60142. /**
  60143. * Creates a refraction texture used by refraction channel of the standard material.
  60144. * @param name the texture name
  60145. * @param size size of the underlying texture
  60146. * @param scene root scene
  60147. */
  60148. var RefractionTexture = /** @class */ (function (_super) {
  60149. __extends(RefractionTexture, _super);
  60150. function RefractionTexture(name, size, scene, generateMipMaps) {
  60151. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60152. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60153. _this.depth = 2.0;
  60154. _this.onBeforeRenderObservable.add(function () {
  60155. scene.clipPlane = _this.refractionPlane;
  60156. });
  60157. _this.onAfterRenderObservable.add(function () {
  60158. delete scene.clipPlane;
  60159. });
  60160. return _this;
  60161. }
  60162. RefractionTexture.prototype.clone = function () {
  60163. var scene = this.getScene();
  60164. if (!scene) {
  60165. return this;
  60166. }
  60167. var textureSize = this.getSize();
  60168. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60169. // Base texture
  60170. newTexture.hasAlpha = this.hasAlpha;
  60171. newTexture.level = this.level;
  60172. // Refraction Texture
  60173. newTexture.refractionPlane = this.refractionPlane.clone();
  60174. if (this.renderList) {
  60175. newTexture.renderList = this.renderList.slice(0);
  60176. }
  60177. newTexture.depth = this.depth;
  60178. return newTexture;
  60179. };
  60180. RefractionTexture.prototype.serialize = function () {
  60181. if (!this.name) {
  60182. return null;
  60183. }
  60184. var serializationObject = _super.prototype.serialize.call(this);
  60185. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60186. serializationObject.depth = this.depth;
  60187. return serializationObject;
  60188. };
  60189. return RefractionTexture;
  60190. }(BABYLON.RenderTargetTexture));
  60191. BABYLON.RefractionTexture = RefractionTexture;
  60192. })(BABYLON || (BABYLON = {}));
  60193. //# sourceMappingURL=babylon.refractionTexture.js.map
  60194. "use strict";
  60195. var BABYLON;
  60196. (function (BABYLON) {
  60197. /**
  60198. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60199. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60200. */
  60201. var DynamicTexture = /** @class */ (function (_super) {
  60202. __extends(DynamicTexture, _super);
  60203. /**
  60204. * Creates a {BABYLON.DynamicTexture}
  60205. * @param name defines the name of the texture
  60206. * @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
  60207. * @param scene defines the scene where you want the texture
  60208. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60209. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60210. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60211. */
  60212. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60213. if (scene === void 0) { scene = null; }
  60214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60215. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60216. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60217. _this.name = name;
  60218. _this._engine = _this.getScene().getEngine();
  60219. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60220. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60221. _this._generateMipMaps = generateMipMaps;
  60222. if (options.getContext) {
  60223. _this._canvas = options;
  60224. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60225. }
  60226. else {
  60227. _this._canvas = document.createElement("canvas");
  60228. if (options.width) {
  60229. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60230. }
  60231. else {
  60232. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60233. }
  60234. }
  60235. var textureSize = _this.getSize();
  60236. _this._canvas.width = textureSize.width;
  60237. _this._canvas.height = textureSize.height;
  60238. _this._context = _this._canvas.getContext("2d");
  60239. return _this;
  60240. }
  60241. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60242. /**
  60243. * Gets the current state of canRescale
  60244. */
  60245. get: function () {
  60246. return true;
  60247. },
  60248. enumerable: true,
  60249. configurable: true
  60250. });
  60251. DynamicTexture.prototype._recreate = function (textureSize) {
  60252. this._canvas.width = textureSize.width;
  60253. this._canvas.height = textureSize.height;
  60254. this.releaseInternalTexture();
  60255. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60256. };
  60257. /**
  60258. * Scales the texture
  60259. * @param ratio the scale factor to apply to both width and height
  60260. */
  60261. DynamicTexture.prototype.scale = function (ratio) {
  60262. var textureSize = this.getSize();
  60263. textureSize.width *= ratio;
  60264. textureSize.height *= ratio;
  60265. this._recreate(textureSize);
  60266. };
  60267. /**
  60268. * Resizes the texture
  60269. * @param width the new width
  60270. * @param height the new height
  60271. */
  60272. DynamicTexture.prototype.scaleTo = function (width, height) {
  60273. var textureSize = this.getSize();
  60274. textureSize.width = width;
  60275. textureSize.height = height;
  60276. this._recreate(textureSize);
  60277. };
  60278. /**
  60279. * Gets the context of the canvas used by the texture
  60280. * @returns the canvas context of the dynamic texture
  60281. */
  60282. DynamicTexture.prototype.getContext = function () {
  60283. return this._context;
  60284. };
  60285. /**
  60286. * Clears the texture
  60287. */
  60288. DynamicTexture.prototype.clear = function () {
  60289. var size = this.getSize();
  60290. this._context.fillRect(0, 0, size.width, size.height);
  60291. };
  60292. /**
  60293. * Updates the texture
  60294. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60295. */
  60296. DynamicTexture.prototype.update = function (invertY) {
  60297. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60298. };
  60299. /**
  60300. * Draws text onto the texture
  60301. * @param text defines the text to be drawn
  60302. * @param x defines the placement of the text from the left
  60303. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60304. * @param font defines the font to be used with font-style, font-size, font-name
  60305. * @param color defines the color used for the text
  60306. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60307. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60308. * @param update defines whether texture is immediately update (default is true)
  60309. */
  60310. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60311. if (update === void 0) { update = true; }
  60312. var size = this.getSize();
  60313. if (clearColor) {
  60314. this._context.fillStyle = clearColor;
  60315. this._context.fillRect(0, 0, size.width, size.height);
  60316. }
  60317. this._context.font = font;
  60318. if (x === null || x === undefined) {
  60319. var textSize = this._context.measureText(text);
  60320. x = (size.width - textSize.width) / 2;
  60321. }
  60322. if (y === null || y === undefined) {
  60323. var fontSize = parseInt((font.replace(/\D/g, '')));
  60324. ;
  60325. y = (size.height / 2) + (fontSize / 3.65);
  60326. }
  60327. this._context.fillStyle = color;
  60328. this._context.fillText(text, x, y);
  60329. if (update) {
  60330. this.update(invertY);
  60331. }
  60332. };
  60333. /**
  60334. * Clones the texture
  60335. * @returns the clone of the texture.
  60336. */
  60337. DynamicTexture.prototype.clone = function () {
  60338. var scene = this.getScene();
  60339. if (!scene) {
  60340. return this;
  60341. }
  60342. var textureSize = this.getSize();
  60343. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60344. // Base texture
  60345. newTexture.hasAlpha = this.hasAlpha;
  60346. newTexture.level = this.level;
  60347. // Dynamic Texture
  60348. newTexture.wrapU = this.wrapU;
  60349. newTexture.wrapV = this.wrapV;
  60350. return newTexture;
  60351. };
  60352. /** @ignore */
  60353. DynamicTexture.prototype._rebuild = function () {
  60354. this.update();
  60355. };
  60356. return DynamicTexture;
  60357. }(BABYLON.Texture));
  60358. BABYLON.DynamicTexture = DynamicTexture;
  60359. })(BABYLON || (BABYLON = {}));
  60360. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60361. "use strict";
  60362. var BABYLON;
  60363. (function (BABYLON) {
  60364. var VideoTexture = /** @class */ (function (_super) {
  60365. __extends(VideoTexture, _super);
  60366. /**
  60367. * Creates a video texture.
  60368. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60369. * @param {string | null} name optional name, will detect from video source, if not defined
  60370. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60371. * @param {BABYLON.Scene} scene is obviously the current scene.
  60372. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60373. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60374. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60375. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60376. */
  60377. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60378. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60379. if (invertY === void 0) { invertY = false; }
  60380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60381. if (settings === void 0) { settings = {
  60382. autoPlay: true,
  60383. loop: true,
  60384. autoUpdateTexture: true,
  60385. }; }
  60386. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60387. _this._createInternalTexture = function () {
  60388. if (_this._texture != null) {
  60389. return;
  60390. }
  60391. if (!_this._engine.needPOTTextures ||
  60392. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60393. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60394. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60395. }
  60396. else {
  60397. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60398. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60399. _this._generateMipMaps = false;
  60400. }
  60401. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60402. _this._texture.isReady = true;
  60403. _this._updateInternalTexture();
  60404. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60405. _this.onLoadObservable.notifyObservers(_this);
  60406. }
  60407. };
  60408. _this.reset = function () {
  60409. if (_this._texture == null) {
  60410. return;
  60411. }
  60412. _this._texture.dispose();
  60413. _this._texture = null;
  60414. };
  60415. _this._updateInternalTexture = function (e) {
  60416. if (_this._texture == null || !_this._texture.isReady) {
  60417. return;
  60418. }
  60419. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60420. return;
  60421. }
  60422. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60423. };
  60424. _this._engine = _this.getScene().getEngine();
  60425. _this._generateMipMaps = generateMipMaps;
  60426. _this._samplingMode = samplingMode;
  60427. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60428. _this.name = name || _this._getName(src);
  60429. _this.video = _this._getVideo(src);
  60430. if (settings.autoPlay !== undefined) {
  60431. _this.video.autoplay = settings.autoPlay;
  60432. }
  60433. if (settings.loop !== undefined) {
  60434. _this.video.loop = settings.loop;
  60435. }
  60436. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60437. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60438. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60439. _this.video.addEventListener("emptied", _this.reset);
  60440. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60441. _this._createInternalTexture();
  60442. }
  60443. return _this;
  60444. }
  60445. VideoTexture.prototype._getName = function (src) {
  60446. if (src instanceof HTMLVideoElement) {
  60447. return src.currentSrc;
  60448. }
  60449. if (typeof src === "object") {
  60450. return src.toString();
  60451. }
  60452. return src;
  60453. };
  60454. ;
  60455. VideoTexture.prototype._getVideo = function (src) {
  60456. if (src instanceof HTMLVideoElement) {
  60457. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60458. return src;
  60459. }
  60460. var video = document.createElement("video");
  60461. if (typeof src === "string") {
  60462. BABYLON.Tools.SetCorsBehavior(src, video);
  60463. video.src = src;
  60464. }
  60465. else {
  60466. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60467. src.forEach(function (url) {
  60468. var source = document.createElement("source");
  60469. source.src = url;
  60470. video.appendChild(source);
  60471. });
  60472. }
  60473. return video;
  60474. };
  60475. ;
  60476. /**
  60477. * Internal method to initiate `update`.
  60478. */
  60479. VideoTexture.prototype._rebuild = function () {
  60480. this.update();
  60481. };
  60482. /**
  60483. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60484. */
  60485. VideoTexture.prototype.update = function () {
  60486. if (!this.autoUpdateTexture) {
  60487. // Expecting user to call `updateTexture` manually
  60488. return;
  60489. }
  60490. this.updateTexture(true);
  60491. };
  60492. /**
  60493. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60494. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60495. */
  60496. VideoTexture.prototype.updateTexture = function (isVisible) {
  60497. if (!isVisible) {
  60498. return;
  60499. }
  60500. if (this.video.paused) {
  60501. return;
  60502. }
  60503. this._updateInternalTexture();
  60504. };
  60505. /**
  60506. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60507. * @param url New url.
  60508. */
  60509. VideoTexture.prototype.updateURL = function (url) {
  60510. this.video.src = url;
  60511. };
  60512. VideoTexture.prototype.dispose = function () {
  60513. _super.prototype.dispose.call(this);
  60514. this.video.removeEventListener("canplay", this._createInternalTexture);
  60515. this.video.removeEventListener("paused", this._updateInternalTexture);
  60516. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60517. this.video.removeEventListener("emptied", this.reset);
  60518. this.video.pause();
  60519. };
  60520. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60521. var video = document.createElement("video");
  60522. var constraintsDeviceId;
  60523. if (constraints && constraints.deviceId) {
  60524. constraintsDeviceId = {
  60525. exact: constraints.deviceId,
  60526. };
  60527. }
  60528. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60529. if (navigator.mediaDevices) {
  60530. navigator.mediaDevices.getUserMedia({ video: constraints })
  60531. .then(function (stream) {
  60532. if (video.mozSrcObject !== undefined) {
  60533. // hack for Firefox < 19
  60534. video.mozSrcObject = stream;
  60535. }
  60536. else {
  60537. video.srcObject = stream;
  60538. }
  60539. var onPlaying = function () {
  60540. if (onReady) {
  60541. onReady(new VideoTexture("video", video, scene, true, true));
  60542. }
  60543. video.removeEventListener("playing", onPlaying);
  60544. };
  60545. video.addEventListener("playing", onPlaying);
  60546. video.play();
  60547. })
  60548. .catch(function (err) {
  60549. BABYLON.Tools.Error(err.name);
  60550. });
  60551. }
  60552. else {
  60553. navigator.getUserMedia =
  60554. navigator.getUserMedia ||
  60555. navigator.webkitGetUserMedia ||
  60556. navigator.mozGetUserMedia ||
  60557. navigator.msGetUserMedia;
  60558. if (navigator.getUserMedia) {
  60559. navigator.getUserMedia({
  60560. video: {
  60561. deviceId: constraintsDeviceId,
  60562. width: {
  60563. min: (constraints && constraints.minWidth) || 256,
  60564. max: (constraints && constraints.maxWidth) || 640,
  60565. },
  60566. height: {
  60567. min: (constraints && constraints.minHeight) || 256,
  60568. max: (constraints && constraints.maxHeight) || 480,
  60569. },
  60570. },
  60571. }, function (stream) {
  60572. if (video.mozSrcObject !== undefined) {
  60573. // hack for Firefox < 19
  60574. video.mozSrcObject = stream;
  60575. }
  60576. else {
  60577. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60578. }
  60579. video.play();
  60580. if (onReady) {
  60581. onReady(new VideoTexture("video", video, scene, true, true));
  60582. }
  60583. }, function (e) {
  60584. BABYLON.Tools.Error(e.name);
  60585. });
  60586. }
  60587. }
  60588. };
  60589. return VideoTexture;
  60590. }(BABYLON.Texture));
  60591. BABYLON.VideoTexture = VideoTexture;
  60592. })(BABYLON || (BABYLON = {}));
  60593. //# sourceMappingURL=babylon.videoTexture.js.map
  60594. "use strict";
  60595. var BABYLON;
  60596. (function (BABYLON) {
  60597. var RawTexture = /** @class */ (function (_super) {
  60598. __extends(RawTexture, _super);
  60599. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60600. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60601. if (invertY === void 0) { invertY = false; }
  60602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60603. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60604. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60605. _this.format = format;
  60606. _this._engine = scene.getEngine();
  60607. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60608. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60609. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60610. return _this;
  60611. }
  60612. RawTexture.prototype.update = function (data) {
  60613. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60614. };
  60615. // Statics
  60616. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60617. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60618. if (invertY === void 0) { invertY = false; }
  60619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60620. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60621. };
  60622. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60624. if (invertY === void 0) { invertY = false; }
  60625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60626. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60627. };
  60628. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60629. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60630. if (invertY === void 0) { invertY = false; }
  60631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60632. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60633. };
  60634. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60635. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60636. if (invertY === void 0) { invertY = false; }
  60637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60638. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60639. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60640. };
  60641. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60642. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60643. if (invertY === void 0) { invertY = false; }
  60644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60645. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60646. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60647. };
  60648. return RawTexture;
  60649. }(BABYLON.Texture));
  60650. BABYLON.RawTexture = RawTexture;
  60651. })(BABYLON || (BABYLON = {}));
  60652. //# sourceMappingURL=babylon.rawTexture.js.map
  60653. "use strict";
  60654. var BABYLON;
  60655. (function (BABYLON) {
  60656. /**
  60657. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60658. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60659. */
  60660. var PostProcess = /** @class */ (function () {
  60661. /**
  60662. * Creates a new instance PostProcess
  60663. * @param name The name of the PostProcess.
  60664. * @param fragmentUrl The url of the fragment shader to be used.
  60665. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60666. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60667. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60668. * @param camera The camera to apply the render pass to.
  60669. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60670. * @param engine The engine which the post process will be applied. (default: current engine)
  60671. * @param reusable If the post process can be reused on the same frame. (default: false)
  60672. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60673. * @param textureType Type of textures used when performing the post process. (default: 0)
  60674. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60675. * @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
  60676. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60677. */
  60678. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60680. if (defines === void 0) { defines = null; }
  60681. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60682. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60683. if (blockCompilation === void 0) { blockCompilation = false; }
  60684. this.name = name;
  60685. /**
  60686. * Width of the texture to apply the post process on
  60687. */
  60688. this.width = -1;
  60689. /**
  60690. * Height of the texture to apply the post process on
  60691. */
  60692. this.height = -1;
  60693. /**
  60694. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60695. */
  60696. this._outputTexture = null;
  60697. /**
  60698. * If the buffer needs to be cleared before applying the post process. (default: true)
  60699. * Should be set to false if shader will overwrite all previous pixels.
  60700. */
  60701. this.autoClear = true;
  60702. /**
  60703. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60704. */
  60705. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60706. /**
  60707. * Animations to be used for the post processing
  60708. */
  60709. this.animations = new Array();
  60710. /**
  60711. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60712. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60713. */
  60714. this.enablePixelPerfectMode = false;
  60715. /**
  60716. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60717. */
  60718. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60719. /**
  60720. * Force textures to be a power of two (default: false)
  60721. */
  60722. this.alwaysForcePOT = false;
  60723. /**
  60724. * Number of sample textures (default: 1)
  60725. */
  60726. this.samples = 1;
  60727. /**
  60728. * Modify the scale of the post process to be the same as the viewport (default: false)
  60729. */
  60730. this.adaptScaleToCurrentViewport = false;
  60731. this._reusable = false;
  60732. /**
  60733. * Smart array of input and output textures for the post process.
  60734. */
  60735. this._textures = new BABYLON.SmartArray(2);
  60736. /**
  60737. * The index in _textures that corresponds to the output texture.
  60738. */
  60739. this._currentRenderTextureInd = 0;
  60740. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60741. this._texelSize = BABYLON.Vector2.Zero();
  60742. // Events
  60743. /**
  60744. * An event triggered when the postprocess is activated.
  60745. * @type {BABYLON.Observable}
  60746. */
  60747. this.onActivateObservable = new BABYLON.Observable();
  60748. /**
  60749. * An event triggered when the postprocess changes its size.
  60750. * @type {BABYLON.Observable}
  60751. */
  60752. this.onSizeChangedObservable = new BABYLON.Observable();
  60753. /**
  60754. * An event triggered when the postprocess applies its effect.
  60755. * @type {BABYLON.Observable}
  60756. */
  60757. this.onApplyObservable = new BABYLON.Observable();
  60758. /**
  60759. * An event triggered before rendering the postprocess
  60760. * @type {BABYLON.Observable}
  60761. */
  60762. this.onBeforeRenderObservable = new BABYLON.Observable();
  60763. /**
  60764. * An event triggered after rendering the postprocess
  60765. * @type {BABYLON.Observable}
  60766. */
  60767. this.onAfterRenderObservable = new BABYLON.Observable();
  60768. if (camera != null) {
  60769. this._camera = camera;
  60770. this._scene = camera.getScene();
  60771. camera.attachPostProcess(this);
  60772. this._engine = this._scene.getEngine();
  60773. this._scene.postProcesses.push(this);
  60774. }
  60775. else if (engine) {
  60776. this._engine = engine;
  60777. this._engine.postProcesses.push(this);
  60778. }
  60779. this._options = options;
  60780. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60781. this._reusable = reusable || false;
  60782. this._textureType = textureType;
  60783. this._samplers = samplers || [];
  60784. this._samplers.push("textureSampler");
  60785. this._fragmentUrl = fragmentUrl;
  60786. this._vertexUrl = vertexUrl;
  60787. this._parameters = parameters || [];
  60788. this._parameters.push("scale");
  60789. this._indexParameters = indexParameters;
  60790. if (!blockCompilation) {
  60791. this.updateEffect(defines);
  60792. }
  60793. }
  60794. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60795. /**
  60796. * A function that is added to the onActivateObservable
  60797. */
  60798. set: function (callback) {
  60799. if (this._onActivateObserver) {
  60800. this.onActivateObservable.remove(this._onActivateObserver);
  60801. }
  60802. if (callback) {
  60803. this._onActivateObserver = this.onActivateObservable.add(callback);
  60804. }
  60805. },
  60806. enumerable: true,
  60807. configurable: true
  60808. });
  60809. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60810. /**
  60811. * A function that is added to the onSizeChangedObservable
  60812. */
  60813. set: function (callback) {
  60814. if (this._onSizeChangedObserver) {
  60815. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60816. }
  60817. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60818. },
  60819. enumerable: true,
  60820. configurable: true
  60821. });
  60822. Object.defineProperty(PostProcess.prototype, "onApply", {
  60823. /**
  60824. * A function that is added to the onApplyObservable
  60825. */
  60826. set: function (callback) {
  60827. if (this._onApplyObserver) {
  60828. this.onApplyObservable.remove(this._onApplyObserver);
  60829. }
  60830. this._onApplyObserver = this.onApplyObservable.add(callback);
  60831. },
  60832. enumerable: true,
  60833. configurable: true
  60834. });
  60835. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60836. /**
  60837. * A function that is added to the onBeforeRenderObservable
  60838. */
  60839. set: function (callback) {
  60840. if (this._onBeforeRenderObserver) {
  60841. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60842. }
  60843. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60844. },
  60845. enumerable: true,
  60846. configurable: true
  60847. });
  60848. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60849. /**
  60850. * A function that is added to the onAfterRenderObservable
  60851. */
  60852. set: function (callback) {
  60853. if (this._onAfterRenderObserver) {
  60854. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60855. }
  60856. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60857. },
  60858. enumerable: true,
  60859. configurable: true
  60860. });
  60861. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60862. /**
  60863. * 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
  60864. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60865. */
  60866. get: function () {
  60867. return this._textures.data[this._currentRenderTextureInd];
  60868. },
  60869. set: function (value) {
  60870. this._forcedOutputTexture = value;
  60871. },
  60872. enumerable: true,
  60873. configurable: true
  60874. });
  60875. /**
  60876. * Gets the camera which post process is applied to.
  60877. * @returns The camera the post process is applied to.
  60878. */
  60879. PostProcess.prototype.getCamera = function () {
  60880. return this._camera;
  60881. };
  60882. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60883. /**
  60884. * Gets the texel size of the postprocess.
  60885. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60886. */
  60887. get: function () {
  60888. if (this._shareOutputWithPostProcess) {
  60889. return this._shareOutputWithPostProcess.texelSize;
  60890. }
  60891. if (this._forcedOutputTexture) {
  60892. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60893. }
  60894. return this._texelSize;
  60895. },
  60896. enumerable: true,
  60897. configurable: true
  60898. });
  60899. /**
  60900. * Gets the engine which this post process belongs to.
  60901. * @returns The engine the post process was enabled with.
  60902. */
  60903. PostProcess.prototype.getEngine = function () {
  60904. return this._engine;
  60905. };
  60906. /**
  60907. * The effect that is created when initializing the post process.
  60908. * @returns The created effect corrisponding the the postprocess.
  60909. */
  60910. PostProcess.prototype.getEffect = function () {
  60911. return this._effect;
  60912. };
  60913. /**
  60914. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60915. * @param postProcess The post process to share the output with.
  60916. * @returns This post process.
  60917. */
  60918. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60919. this._disposeTextures();
  60920. this._shareOutputWithPostProcess = postProcess;
  60921. return this;
  60922. };
  60923. /**
  60924. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60925. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60926. */
  60927. PostProcess.prototype.useOwnOutput = function () {
  60928. if (this._textures.length == 0) {
  60929. this._textures = new BABYLON.SmartArray(2);
  60930. }
  60931. this._shareOutputWithPostProcess = null;
  60932. };
  60933. /**
  60934. * Updates the effect with the current post process compile time values and recompiles the shader.
  60935. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60936. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60937. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60938. * @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
  60939. * @param onCompiled Called when the shader has been compiled.
  60940. * @param onError Called if there is an error when compiling a shader.
  60941. */
  60942. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60943. if (defines === void 0) { defines = null; }
  60944. if (uniforms === void 0) { uniforms = null; }
  60945. if (samplers === void 0) { samplers = null; }
  60946. 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);
  60947. };
  60948. /**
  60949. * The post process is reusable if it can be used multiple times within one frame.
  60950. * @returns If the post process is reusable
  60951. */
  60952. PostProcess.prototype.isReusable = function () {
  60953. return this._reusable;
  60954. };
  60955. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60956. PostProcess.prototype.markTextureDirty = function () {
  60957. this.width = -1;
  60958. };
  60959. /**
  60960. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60961. * 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.
  60962. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60963. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60964. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60965. * @returns The target texture that was bound to be written to.
  60966. */
  60967. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60968. var _this = this;
  60969. if (sourceTexture === void 0) { sourceTexture = null; }
  60970. camera = camera || this._camera;
  60971. var scene = camera.getScene();
  60972. var engine = scene.getEngine();
  60973. var maxSize = engine.getCaps().maxTextureSize;
  60974. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60975. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60976. // 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
  60977. var webVRCamera = camera.parent;
  60978. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60979. requiredWidth /= 2;
  60980. }
  60981. var desiredWidth = (this._options.width || requiredWidth);
  60982. var desiredHeight = this._options.height || requiredHeight;
  60983. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60984. if (this.adaptScaleToCurrentViewport) {
  60985. var currentViewport = engine.currentViewport;
  60986. if (currentViewport) {
  60987. desiredWidth *= currentViewport.width;
  60988. desiredHeight *= currentViewport.height;
  60989. }
  60990. }
  60991. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60992. if (!this._options.width) {
  60993. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60994. }
  60995. if (!this._options.height) {
  60996. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60997. }
  60998. }
  60999. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  61000. if (this._textures.length > 0) {
  61001. for (var i = 0; i < this._textures.length; i++) {
  61002. this._engine._releaseTexture(this._textures.data[i]);
  61003. }
  61004. this._textures.reset();
  61005. }
  61006. this.width = desiredWidth;
  61007. this.height = desiredHeight;
  61008. var textureSize = { width: this.width, height: this.height };
  61009. var textureOptions = {
  61010. generateMipMaps: false,
  61011. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  61012. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  61013. samplingMode: this.renderTargetSamplingMode,
  61014. type: this._textureType
  61015. };
  61016. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61017. if (this._reusable) {
  61018. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61019. }
  61020. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  61021. this.onSizeChangedObservable.notifyObservers(this);
  61022. }
  61023. this._textures.forEach(function (texture) {
  61024. if (texture.samples !== _this.samples) {
  61025. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  61026. }
  61027. });
  61028. }
  61029. var target;
  61030. if (this._shareOutputWithPostProcess) {
  61031. target = this._shareOutputWithPostProcess.inputTexture;
  61032. }
  61033. else if (this._forcedOutputTexture) {
  61034. target = this._forcedOutputTexture;
  61035. this.width = this._forcedOutputTexture.width;
  61036. this.height = this._forcedOutputTexture.height;
  61037. }
  61038. else {
  61039. target = this.inputTexture;
  61040. }
  61041. // Bind the input of this post process to be used as the output of the previous post process.
  61042. if (this.enablePixelPerfectMode) {
  61043. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  61044. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  61045. }
  61046. else {
  61047. this._scaleRatio.copyFromFloats(1, 1);
  61048. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  61049. }
  61050. this.onActivateObservable.notifyObservers(camera);
  61051. // Clear
  61052. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61053. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61054. }
  61055. if (this._reusable) {
  61056. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61057. }
  61058. return target;
  61059. };
  61060. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61061. /**
  61062. * If the post process is supported.
  61063. */
  61064. get: function () {
  61065. return this._effect.isSupported;
  61066. },
  61067. enumerable: true,
  61068. configurable: true
  61069. });
  61070. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61071. /**
  61072. * The aspect ratio of the output texture.
  61073. */
  61074. get: function () {
  61075. if (this._shareOutputWithPostProcess) {
  61076. return this._shareOutputWithPostProcess.aspectRatio;
  61077. }
  61078. if (this._forcedOutputTexture) {
  61079. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61080. }
  61081. return this.width / this.height;
  61082. },
  61083. enumerable: true,
  61084. configurable: true
  61085. });
  61086. /**
  61087. * Get a value indicating if the post-process is ready to be used
  61088. * @returns true if the post-process is ready (shader is compiled)
  61089. */
  61090. PostProcess.prototype.isReady = function () {
  61091. return this._effect && this._effect.isReady();
  61092. };
  61093. /**
  61094. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61095. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61096. */
  61097. PostProcess.prototype.apply = function () {
  61098. // Check
  61099. if (!this._effect || !this._effect.isReady())
  61100. return null;
  61101. // States
  61102. this._engine.enableEffect(this._effect);
  61103. this._engine.setState(false);
  61104. this._engine.setDepthBuffer(false);
  61105. this._engine.setDepthWrite(false);
  61106. // Alpha
  61107. this._engine.setAlphaMode(this.alphaMode);
  61108. if (this.alphaConstants) {
  61109. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61110. }
  61111. // Bind the output texture of the preivous post process as the input to this post process.
  61112. var source;
  61113. if (this._shareOutputWithPostProcess) {
  61114. source = this._shareOutputWithPostProcess.inputTexture;
  61115. }
  61116. else if (this._forcedOutputTexture) {
  61117. source = this._forcedOutputTexture;
  61118. }
  61119. else {
  61120. source = this.inputTexture;
  61121. }
  61122. this._effect._bindTexture("textureSampler", source);
  61123. // Parameters
  61124. this._effect.setVector2("scale", this._scaleRatio);
  61125. this.onApplyObservable.notifyObservers(this._effect);
  61126. return this._effect;
  61127. };
  61128. PostProcess.prototype._disposeTextures = function () {
  61129. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61130. return;
  61131. }
  61132. if (this._textures.length > 0) {
  61133. for (var i = 0; i < this._textures.length; i++) {
  61134. this._engine._releaseTexture(this._textures.data[i]);
  61135. }
  61136. }
  61137. this._textures.dispose();
  61138. };
  61139. /**
  61140. * Disposes the post process.
  61141. * @param camera The camera to dispose the post process on.
  61142. */
  61143. PostProcess.prototype.dispose = function (camera) {
  61144. camera = camera || this._camera;
  61145. this._disposeTextures();
  61146. if (this._scene) {
  61147. var index_1 = this._scene.postProcesses.indexOf(this);
  61148. if (index_1 !== -1) {
  61149. this._scene.postProcesses.splice(index_1, 1);
  61150. }
  61151. }
  61152. else {
  61153. var index_2 = this._engine.postProcesses.indexOf(this);
  61154. if (index_2 !== -1) {
  61155. this._engine.postProcesses.splice(index_2, 1);
  61156. }
  61157. }
  61158. if (!camera) {
  61159. return;
  61160. }
  61161. camera.detachPostProcess(this);
  61162. var index = camera._postProcesses.indexOf(this);
  61163. if (index === 0 && camera._postProcesses.length > 0) {
  61164. var firstPostProcess = this._camera._getFirstPostProcess();
  61165. if (firstPostProcess) {
  61166. firstPostProcess.markTextureDirty();
  61167. }
  61168. }
  61169. this.onActivateObservable.clear();
  61170. this.onAfterRenderObservable.clear();
  61171. this.onApplyObservable.clear();
  61172. this.onBeforeRenderObservable.clear();
  61173. this.onSizeChangedObservable.clear();
  61174. };
  61175. return PostProcess;
  61176. }());
  61177. BABYLON.PostProcess = PostProcess;
  61178. })(BABYLON || (BABYLON = {}));
  61179. //# sourceMappingURL=babylon.postProcess.js.map
  61180. "use strict";
  61181. var BABYLON;
  61182. (function (BABYLON) {
  61183. var PassPostProcess = /** @class */ (function (_super) {
  61184. __extends(PassPostProcess, _super);
  61185. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61186. if (camera === void 0) { camera = null; }
  61187. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61188. if (blockCompilation === void 0) { blockCompilation = false; }
  61189. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61190. }
  61191. return PassPostProcess;
  61192. }(BABYLON.PostProcess));
  61193. BABYLON.PassPostProcess = PassPostProcess;
  61194. })(BABYLON || (BABYLON = {}));
  61195. //# sourceMappingURL=babylon.passPostProcess.js.map
  61196. "use strict";
  61197. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61198. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61199. s = arguments[i];
  61200. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61201. t[p] = s[p];
  61202. }
  61203. return t;
  61204. };
  61205. var BABYLON;
  61206. (function (BABYLON) {
  61207. /**
  61208. * Default implementation IShadowGenerator.
  61209. * This is the main object responsible of generating shadows in the framework.
  61210. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61211. */
  61212. var ShadowGenerator = /** @class */ (function () {
  61213. /**
  61214. * Creates a ShadowGenerator object.
  61215. * A ShadowGenerator is the required tool to use the shadows.
  61216. * Each light casting shadows needs to use its own ShadowGenerator.
  61217. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61218. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61219. * @param light The light object generating the shadows.
  61220. * @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.
  61221. */
  61222. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61223. this._bias = 0.00005;
  61224. this._normalBias = 0;
  61225. this._blurBoxOffset = 1;
  61226. this._blurScale = 2;
  61227. this._blurKernel = 1;
  61228. this._useKernelBlur = false;
  61229. this._filter = ShadowGenerator.FILTER_NONE;
  61230. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61231. this._contactHardeningLightSizeUVRatio = 0.1;
  61232. this._darkness = 0;
  61233. this._transparencyShadow = false;
  61234. /**
  61235. * Controls the extent to which the shadows fade out at the edge of the frustum
  61236. * Used only by directionals and spots
  61237. */
  61238. this.frustumEdgeFalloff = 0;
  61239. /**
  61240. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61241. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61242. * It might on the other hand introduce peter panning.
  61243. */
  61244. this.forceBackFacesOnly = false;
  61245. this._lightDirection = BABYLON.Vector3.Zero();
  61246. this._viewMatrix = BABYLON.Matrix.Zero();
  61247. this._projectionMatrix = BABYLON.Matrix.Zero();
  61248. this._transformMatrix = BABYLON.Matrix.Zero();
  61249. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61250. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61251. this._currentFaceIndex = 0;
  61252. this._currentFaceIndexCache = 0;
  61253. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61254. this._mapSize = mapSize;
  61255. this._light = light;
  61256. this._scene = light.getScene();
  61257. light._shadowGenerator = this;
  61258. // Texture type fallback from float to int if not supported.
  61259. var caps = this._scene.getEngine().getCaps();
  61260. if (!useFullFloatFirst) {
  61261. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61262. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61263. }
  61264. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61265. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61266. }
  61267. else {
  61268. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61269. }
  61270. }
  61271. else {
  61272. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61273. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61274. }
  61275. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61276. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61277. }
  61278. else {
  61279. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61280. }
  61281. }
  61282. this._initializeGenerator();
  61283. this._applyFilterValues();
  61284. }
  61285. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61286. /**
  61287. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61288. */
  61289. get: function () {
  61290. return this._bias;
  61291. },
  61292. /**
  61293. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61294. */
  61295. set: function (bias) {
  61296. this._bias = bias;
  61297. },
  61298. enumerable: true,
  61299. configurable: true
  61300. });
  61301. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61302. /**
  61303. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61304. */
  61305. get: function () {
  61306. return this._normalBias;
  61307. },
  61308. /**
  61309. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61310. */
  61311. set: function (normalBias) {
  61312. this._normalBias = normalBias;
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61318. /**
  61319. * Gets the blur box offset: offset applied during the blur pass.
  61320. * Only usefull if useKernelBlur = false
  61321. */
  61322. get: function () {
  61323. return this._blurBoxOffset;
  61324. },
  61325. /**
  61326. * Sets the blur box offset: offset applied during the blur pass.
  61327. * Only usefull if useKernelBlur = false
  61328. */
  61329. set: function (value) {
  61330. if (this._blurBoxOffset === value) {
  61331. return;
  61332. }
  61333. this._blurBoxOffset = value;
  61334. this._disposeBlurPostProcesses();
  61335. },
  61336. enumerable: true,
  61337. configurable: true
  61338. });
  61339. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61340. /**
  61341. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61342. * 2 means half of the size.
  61343. */
  61344. get: function () {
  61345. return this._blurScale;
  61346. },
  61347. /**
  61348. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61349. * 2 means half of the size.
  61350. */
  61351. set: function (value) {
  61352. if (this._blurScale === value) {
  61353. return;
  61354. }
  61355. this._blurScale = value;
  61356. this._disposeBlurPostProcesses();
  61357. },
  61358. enumerable: true,
  61359. configurable: true
  61360. });
  61361. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61362. /**
  61363. * Gets the blur kernel: kernel size of the blur pass.
  61364. * Only usefull if useKernelBlur = true
  61365. */
  61366. get: function () {
  61367. return this._blurKernel;
  61368. },
  61369. /**
  61370. * Sets the blur kernel: kernel size of the blur pass.
  61371. * Only usefull if useKernelBlur = true
  61372. */
  61373. set: function (value) {
  61374. if (this._blurKernel === value) {
  61375. return;
  61376. }
  61377. this._blurKernel = value;
  61378. this._disposeBlurPostProcesses();
  61379. },
  61380. enumerable: true,
  61381. configurable: true
  61382. });
  61383. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61384. /**
  61385. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61386. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61387. */
  61388. get: function () {
  61389. return this._useKernelBlur;
  61390. },
  61391. /**
  61392. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61393. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61394. */
  61395. set: function (value) {
  61396. if (this._useKernelBlur === value) {
  61397. return;
  61398. }
  61399. this._useKernelBlur = value;
  61400. this._disposeBlurPostProcesses();
  61401. },
  61402. enumerable: true,
  61403. configurable: true
  61404. });
  61405. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61406. /**
  61407. * Gets the depth scale used in ESM mode.
  61408. */
  61409. get: function () {
  61410. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61411. },
  61412. /**
  61413. * Sets the depth scale used in ESM mode.
  61414. * This can override the scale stored on the light.
  61415. */
  61416. set: function (value) {
  61417. this._depthScale = value;
  61418. },
  61419. enumerable: true,
  61420. configurable: true
  61421. });
  61422. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61423. /**
  61424. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61425. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61426. */
  61427. get: function () {
  61428. return this._filter;
  61429. },
  61430. /**
  61431. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61432. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61433. */
  61434. set: function (value) {
  61435. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61436. if (this._light.needCube()) {
  61437. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61438. this.useExponentialShadowMap = true;
  61439. return;
  61440. }
  61441. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61442. this.useCloseExponentialShadowMap = true;
  61443. return;
  61444. }
  61445. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61446. this.usePoissonSampling = true;
  61447. return;
  61448. }
  61449. }
  61450. // Weblg1 fallback for PCF.
  61451. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61452. if (this._scene.getEngine().webGLVersion === 1) {
  61453. this.usePoissonSampling = true;
  61454. return;
  61455. }
  61456. }
  61457. if (this._filter === value) {
  61458. return;
  61459. }
  61460. this._filter = value;
  61461. this._disposeBlurPostProcesses();
  61462. this._applyFilterValues();
  61463. this._light._markMeshesAsLightDirty();
  61464. },
  61465. enumerable: true,
  61466. configurable: true
  61467. });
  61468. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61469. /**
  61470. * Gets if the current filter is set to Poisson Sampling.
  61471. */
  61472. get: function () {
  61473. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61474. },
  61475. /**
  61476. * Sets the current filter to Poisson Sampling.
  61477. */
  61478. set: function (value) {
  61479. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61480. return;
  61481. }
  61482. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61483. },
  61484. enumerable: true,
  61485. configurable: true
  61486. });
  61487. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61488. /**
  61489. * Gets if the current filter is set to VSM.
  61490. * DEPRECATED. Should use useExponentialShadowMap instead.
  61491. */
  61492. get: function () {
  61493. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61494. return this.useExponentialShadowMap;
  61495. },
  61496. /**
  61497. * Sets the current filter is to VSM.
  61498. * DEPRECATED. Should use useExponentialShadowMap instead.
  61499. */
  61500. set: function (value) {
  61501. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61502. this.useExponentialShadowMap = value;
  61503. },
  61504. enumerable: true,
  61505. configurable: true
  61506. });
  61507. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61508. /**
  61509. * Gets if the current filter is set to blurred VSM.
  61510. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61511. */
  61512. get: function () {
  61513. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61514. return this.useBlurExponentialShadowMap;
  61515. },
  61516. /**
  61517. * Sets the current filter is to blurred VSM.
  61518. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61519. */
  61520. set: function (value) {
  61521. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61522. this.useBlurExponentialShadowMap = value;
  61523. },
  61524. enumerable: true,
  61525. configurable: true
  61526. });
  61527. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61528. /**
  61529. * Gets if the current filter is set to ESM.
  61530. */
  61531. get: function () {
  61532. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61533. },
  61534. /**
  61535. * Sets the current filter is to ESM.
  61536. */
  61537. set: function (value) {
  61538. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61539. return;
  61540. }
  61541. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61542. },
  61543. enumerable: true,
  61544. configurable: true
  61545. });
  61546. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61547. /**
  61548. * Gets if the current filter is set to filtered ESM.
  61549. */
  61550. get: function () {
  61551. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61552. },
  61553. /**
  61554. * Gets if the current filter is set to filtered ESM.
  61555. */
  61556. set: function (value) {
  61557. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61558. return;
  61559. }
  61560. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61561. },
  61562. enumerable: true,
  61563. configurable: true
  61564. });
  61565. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61566. /**
  61567. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61568. * exponential to prevent steep falloff artifacts).
  61569. */
  61570. get: function () {
  61571. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61572. },
  61573. /**
  61574. * Sets the current filter to "close ESM" (using the inverse of the
  61575. * exponential to prevent steep falloff artifacts).
  61576. */
  61577. set: function (value) {
  61578. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61579. return;
  61580. }
  61581. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61582. },
  61583. enumerable: true,
  61584. configurable: true
  61585. });
  61586. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61587. /**
  61588. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61589. * exponential to prevent steep falloff artifacts).
  61590. */
  61591. get: function () {
  61592. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61593. },
  61594. /**
  61595. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61596. * exponential to prevent steep falloff artifacts).
  61597. */
  61598. set: function (value) {
  61599. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61600. return;
  61601. }
  61602. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61603. },
  61604. enumerable: true,
  61605. configurable: true
  61606. });
  61607. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61608. /**
  61609. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61610. */
  61611. get: function () {
  61612. return this.filter === ShadowGenerator.FILTER_PCF;
  61613. },
  61614. /**
  61615. * Sets the current filter to "PCF" (percentage closer filtering).
  61616. */
  61617. set: function (value) {
  61618. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61619. return;
  61620. }
  61621. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61622. },
  61623. enumerable: true,
  61624. configurable: true
  61625. });
  61626. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61627. /**
  61628. * Gets the PCF or PCSS Quality.
  61629. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61630. */
  61631. get: function () {
  61632. return this._filteringQuality;
  61633. },
  61634. /**
  61635. * Sets the PCF or PCSS Quality.
  61636. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61637. */
  61638. set: function (filteringQuality) {
  61639. this._filteringQuality = filteringQuality;
  61640. },
  61641. enumerable: true,
  61642. configurable: true
  61643. });
  61644. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61645. /**
  61646. * Gets if the current filter is set to "PCSS" (contact hardening).
  61647. */
  61648. get: function () {
  61649. return this.filter === ShadowGenerator.FILTER_PCSS;
  61650. },
  61651. /**
  61652. * Sets the current filter to "PCSS" (contact hardening).
  61653. */
  61654. set: function (value) {
  61655. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61656. return;
  61657. }
  61658. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61659. },
  61660. enumerable: true,
  61661. configurable: true
  61662. });
  61663. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61664. /**
  61665. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61666. * Using a ratio helps keeping shape stability independently of the map size.
  61667. *
  61668. * It does not account for the light projection as it was having too much
  61669. * instability during the light setup or during light position changes.
  61670. *
  61671. * Only valid if useContactHardeningShadow is true.
  61672. */
  61673. get: function () {
  61674. return this._contactHardeningLightSizeUVRatio;
  61675. },
  61676. /**
  61677. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61678. * Using a ratio helps keeping shape stability independently of the map size.
  61679. *
  61680. * It does not account for the light projection as it was having too much
  61681. * instability during the light setup or during light position changes.
  61682. *
  61683. * Only valid if useContactHardeningShadow is true.
  61684. */
  61685. set: function (contactHardeningLightSizeUVRatio) {
  61686. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61687. },
  61688. enumerable: true,
  61689. configurable: true
  61690. });
  61691. /**
  61692. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61693. * 0 means strongest and 1 would means no shadow.
  61694. * @returns the darkness.
  61695. */
  61696. ShadowGenerator.prototype.getDarkness = function () {
  61697. return this._darkness;
  61698. };
  61699. /**
  61700. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61701. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61702. * @returns the shadow generator allowing fluent coding.
  61703. */
  61704. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61705. if (darkness >= 1.0)
  61706. this._darkness = 1.0;
  61707. else if (darkness <= 0.0)
  61708. this._darkness = 0.0;
  61709. else
  61710. this._darkness = darkness;
  61711. return this;
  61712. };
  61713. /**
  61714. * Sets the ability to have transparent shadow (boolean).
  61715. * @param transparent True if transparent else False
  61716. * @returns the shadow generator allowing fluent coding
  61717. */
  61718. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61719. this._transparencyShadow = transparent;
  61720. return this;
  61721. };
  61722. /**
  61723. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61724. * @returns The render target texture if present otherwise, null
  61725. */
  61726. ShadowGenerator.prototype.getShadowMap = function () {
  61727. return this._shadowMap;
  61728. };
  61729. /**
  61730. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61731. * @returns The render target texture if the shadow map is present otherwise, null
  61732. */
  61733. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61734. if (this._shadowMap2) {
  61735. return this._shadowMap2;
  61736. }
  61737. return this._shadowMap;
  61738. };
  61739. /**
  61740. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61741. * @param mesh Mesh to add
  61742. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61743. * @returns the Shadow Generator itself
  61744. */
  61745. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61746. if (includeDescendants === void 0) { includeDescendants = true; }
  61747. if (!this._shadowMap) {
  61748. return this;
  61749. }
  61750. if (!this._shadowMap.renderList) {
  61751. this._shadowMap.renderList = [];
  61752. }
  61753. this._shadowMap.renderList.push(mesh);
  61754. if (includeDescendants) {
  61755. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61756. }
  61757. return this;
  61758. var _a;
  61759. };
  61760. /**
  61761. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61762. * @param mesh Mesh to remove
  61763. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61764. * @returns the Shadow Generator itself
  61765. */
  61766. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61767. if (includeDescendants === void 0) { includeDescendants = true; }
  61768. if (!this._shadowMap || !this._shadowMap.renderList) {
  61769. return this;
  61770. }
  61771. var index = this._shadowMap.renderList.indexOf(mesh);
  61772. if (index !== -1) {
  61773. this._shadowMap.renderList.splice(index, 1);
  61774. }
  61775. if (includeDescendants) {
  61776. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61777. var child = _a[_i];
  61778. this.removeShadowCaster(child);
  61779. }
  61780. }
  61781. return this;
  61782. };
  61783. /**
  61784. * Returns the associated light object.
  61785. * @returns the light generating the shadow
  61786. */
  61787. ShadowGenerator.prototype.getLight = function () {
  61788. return this._light;
  61789. };
  61790. ShadowGenerator.prototype._initializeGenerator = function () {
  61791. this._light._markMeshesAsLightDirty();
  61792. this._initializeShadowMap();
  61793. };
  61794. ShadowGenerator.prototype._initializeShadowMap = function () {
  61795. var _this = this;
  61796. // Render target
  61797. var engine = this._scene.getEngine();
  61798. if (engine.webGLVersion > 1) {
  61799. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61800. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61801. }
  61802. else {
  61803. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61804. }
  61805. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61806. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61807. this._shadowMap.anisotropicFilteringLevel = 1;
  61808. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61809. this._shadowMap.renderParticles = false;
  61810. this._shadowMap.ignoreCameraViewport = true;
  61811. // Record Face Index before render.
  61812. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61813. _this._currentFaceIndex = faceIndex;
  61814. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61815. engine.setColorWrite(false);
  61816. }
  61817. });
  61818. // Custom render function.
  61819. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61820. // Blur if required afer render.
  61821. this._shadowMap.onAfterUnbindObservable.add(function () {
  61822. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61823. engine.setColorWrite(true);
  61824. }
  61825. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61826. return;
  61827. }
  61828. var shadowMap = _this.getShadowMapForRendering();
  61829. if (shadowMap) {
  61830. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61831. }
  61832. });
  61833. // Clear according to the chosen filter.
  61834. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61835. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61836. this._shadowMap.onClearObservable.add(function (engine) {
  61837. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61838. engine.clear(clearOne, false, true, false);
  61839. }
  61840. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61841. engine.clear(clearZero, true, true, false);
  61842. }
  61843. else {
  61844. engine.clear(clearOne, true, true, false);
  61845. }
  61846. });
  61847. };
  61848. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61849. var _this = this;
  61850. var engine = this._scene.getEngine();
  61851. var targetSize = this._mapSize / this.blurScale;
  61852. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61853. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61854. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61855. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61856. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61857. }
  61858. if (this.useKernelBlur) {
  61859. 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);
  61860. this._kernelBlurXPostprocess.width = targetSize;
  61861. this._kernelBlurXPostprocess.height = targetSize;
  61862. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61863. effect.setTexture("textureSampler", _this._shadowMap);
  61864. });
  61865. 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);
  61866. this._kernelBlurXPostprocess.autoClear = false;
  61867. this._kernelBlurYPostprocess.autoClear = false;
  61868. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61869. this._kernelBlurXPostprocess.packedFloat = true;
  61870. this._kernelBlurYPostprocess.packedFloat = true;
  61871. }
  61872. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61873. }
  61874. else {
  61875. 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);
  61876. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61877. effect.setFloat2("screenSize", targetSize, targetSize);
  61878. effect.setTexture("textureSampler", _this._shadowMap);
  61879. });
  61880. this._boxBlurPostprocess.autoClear = false;
  61881. this._blurPostProcesses = [this._boxBlurPostprocess];
  61882. }
  61883. };
  61884. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61885. var index;
  61886. var engine = this._scene.getEngine();
  61887. if (depthOnlySubMeshes.length) {
  61888. engine.setColorWrite(false);
  61889. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61890. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61891. }
  61892. engine.setColorWrite(true);
  61893. }
  61894. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61895. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61896. }
  61897. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61898. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61899. }
  61900. if (this._transparencyShadow) {
  61901. for (index = 0; index < transparentSubMeshes.length; index++) {
  61902. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61903. }
  61904. }
  61905. };
  61906. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61907. var _this = this;
  61908. var mesh = subMesh.getRenderingMesh();
  61909. var scene = this._scene;
  61910. var engine = scene.getEngine();
  61911. var material = subMesh.getMaterial();
  61912. if (!material) {
  61913. return;
  61914. }
  61915. // Culling
  61916. engine.setState(material.backFaceCulling);
  61917. // Managing instances
  61918. var batch = mesh._getInstancesRenderList(subMesh._id);
  61919. if (batch.mustReturn) {
  61920. return;
  61921. }
  61922. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61923. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61924. engine.enableEffect(this._effect);
  61925. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61926. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61927. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61928. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61929. this._effect.setVector3("lightData", this._cachedDirection);
  61930. }
  61931. else {
  61932. this._effect.setVector3("lightData", this._cachedPosition);
  61933. }
  61934. if (scene.activeCamera) {
  61935. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61936. }
  61937. // Alpha test
  61938. if (material && material.needAlphaTesting()) {
  61939. var alphaTexture = material.getAlphaTestTexture();
  61940. if (alphaTexture) {
  61941. this._effect.setTexture("diffuseSampler", alphaTexture);
  61942. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61943. }
  61944. }
  61945. // Bones
  61946. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61947. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61948. }
  61949. // Morph targets
  61950. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61951. if (this.forceBackFacesOnly) {
  61952. engine.setState(true, 0, false, true);
  61953. }
  61954. // Draw
  61955. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61956. if (this.forceBackFacesOnly) {
  61957. engine.setState(true, 0, false, false);
  61958. }
  61959. }
  61960. else {
  61961. // Need to reset refresh rate of the shadowMap
  61962. if (this._shadowMap) {
  61963. this._shadowMap.resetRefreshCounter();
  61964. }
  61965. }
  61966. };
  61967. ShadowGenerator.prototype._applyFilterValues = function () {
  61968. if (!this._shadowMap) {
  61969. return;
  61970. }
  61971. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61972. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61973. }
  61974. else {
  61975. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61976. }
  61977. };
  61978. /**
  61979. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61980. * @param onCompiled Callback triggered at the and of the effects compilation
  61981. * @param options Sets of optional options forcing the compilation with different modes
  61982. */
  61983. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61984. var _this = this;
  61985. var localOptions = __assign({ useInstances: false }, options);
  61986. var shadowMap = this.getShadowMap();
  61987. if (!shadowMap) {
  61988. if (onCompiled) {
  61989. onCompiled(this);
  61990. }
  61991. return;
  61992. }
  61993. var renderList = shadowMap.renderList;
  61994. if (!renderList) {
  61995. if (onCompiled) {
  61996. onCompiled(this);
  61997. }
  61998. return;
  61999. }
  62000. var subMeshes = new Array();
  62001. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  62002. var mesh = renderList_1[_i];
  62003. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  62004. }
  62005. if (subMeshes.length === 0) {
  62006. if (onCompiled) {
  62007. onCompiled(this);
  62008. }
  62009. return;
  62010. }
  62011. var currentIndex = 0;
  62012. var checkReady = function () {
  62013. if (!_this._scene || !_this._scene.getEngine()) {
  62014. return;
  62015. }
  62016. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  62017. currentIndex++;
  62018. if (currentIndex >= subMeshes.length) {
  62019. if (onCompiled) {
  62020. onCompiled(_this);
  62021. }
  62022. return;
  62023. }
  62024. }
  62025. setTimeout(checkReady, 16);
  62026. };
  62027. checkReady();
  62028. };
  62029. /**
  62030. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62031. * @param options Sets of optional options forcing the compilation with different modes
  62032. * @returns A promise that resolves when the compilation completes
  62033. */
  62034. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  62035. var _this = this;
  62036. return new Promise(function (resolve) {
  62037. _this.forceCompilation(function () {
  62038. resolve();
  62039. }, options);
  62040. });
  62041. };
  62042. /**
  62043. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62044. * @param subMesh The submesh we want to render in the shadow map
  62045. * @param useInstances Defines wether will draw in the map using instances
  62046. * @returns true if ready otherwise, false
  62047. */
  62048. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  62049. var defines = [];
  62050. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62051. defines.push("#define FLOAT");
  62052. }
  62053. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62054. defines.push("#define ESM");
  62055. }
  62056. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62057. defines.push("#define DEPTHTEXTURE");
  62058. }
  62059. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62060. var mesh = subMesh.getMesh();
  62061. var material = subMesh.getMaterial();
  62062. // Normal bias.
  62063. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62064. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62065. defines.push("#define NORMAL");
  62066. if (mesh.nonUniformScaling) {
  62067. defines.push("#define NONUNIFORMSCALING");
  62068. }
  62069. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62070. defines.push("#define DIRECTIONINLIGHTDATA");
  62071. }
  62072. }
  62073. // Alpha test
  62074. if (material && material.needAlphaTesting()) {
  62075. var alphaTexture = material.getAlphaTestTexture();
  62076. if (alphaTexture) {
  62077. defines.push("#define ALPHATEST");
  62078. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62079. attribs.push(BABYLON.VertexBuffer.UVKind);
  62080. defines.push("#define UV1");
  62081. }
  62082. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62083. if (alphaTexture.coordinatesIndex === 1) {
  62084. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62085. defines.push("#define UV2");
  62086. }
  62087. }
  62088. }
  62089. }
  62090. // Bones
  62091. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62092. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62093. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62094. if (mesh.numBoneInfluencers > 4) {
  62095. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62096. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62097. }
  62098. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62099. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62100. }
  62101. else {
  62102. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62103. }
  62104. // Morph targets
  62105. var manager = mesh.morphTargetManager;
  62106. var morphInfluencers = 0;
  62107. if (manager) {
  62108. if (manager.numInfluencers > 0) {
  62109. defines.push("#define MORPHTARGETS");
  62110. morphInfluencers = manager.numInfluencers;
  62111. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62112. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62113. }
  62114. }
  62115. // Instances
  62116. if (useInstances) {
  62117. defines.push("#define INSTANCES");
  62118. attribs.push("world0");
  62119. attribs.push("world1");
  62120. attribs.push("world2");
  62121. attribs.push("world3");
  62122. }
  62123. // Get correct effect
  62124. var join = defines.join("\n");
  62125. if (this._cachedDefines !== join) {
  62126. this._cachedDefines = join;
  62127. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62128. }
  62129. if (!this._effect.isReady()) {
  62130. return false;
  62131. }
  62132. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62133. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62134. this._initializeBlurRTTAndPostProcesses();
  62135. }
  62136. }
  62137. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62138. return false;
  62139. }
  62140. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62141. return false;
  62142. }
  62143. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62144. return false;
  62145. }
  62146. return true;
  62147. };
  62148. /**
  62149. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62150. * @param defines Defines of the material we want to update
  62151. * @param lightIndex Index of the light in the enabled light list of the material
  62152. */
  62153. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62154. var scene = this._scene;
  62155. var light = this._light;
  62156. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62157. return;
  62158. }
  62159. defines["SHADOW" + lightIndex] = true;
  62160. if (this.useContactHardeningShadow) {
  62161. defines["SHADOWPCSS" + lightIndex] = true;
  62162. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62163. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62164. }
  62165. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62166. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62167. }
  62168. // else default to high.
  62169. }
  62170. if (this.usePercentageCloserFiltering) {
  62171. defines["SHADOWPCF" + lightIndex] = true;
  62172. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62173. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62174. }
  62175. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62176. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62177. }
  62178. // else default to high.
  62179. }
  62180. else if (this.usePoissonSampling) {
  62181. defines["SHADOWPOISSON" + lightIndex] = true;
  62182. }
  62183. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62184. defines["SHADOWESM" + lightIndex] = true;
  62185. }
  62186. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62187. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62188. }
  62189. if (light.needCube()) {
  62190. defines["SHADOWCUBE" + lightIndex] = true;
  62191. }
  62192. };
  62193. /**
  62194. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62195. * defined in the generator but impacting the effect).
  62196. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62197. * @param effect The effect we are binfing the information for
  62198. */
  62199. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62200. var light = this._light;
  62201. var scene = this._scene;
  62202. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62203. return;
  62204. }
  62205. var camera = scene.activeCamera;
  62206. if (!camera) {
  62207. return;
  62208. }
  62209. var shadowMap = this.getShadowMap();
  62210. if (!shadowMap) {
  62211. return;
  62212. }
  62213. if (!light.needCube()) {
  62214. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62215. }
  62216. // Only PCF uses depth stencil texture.
  62217. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62218. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62219. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62220. }
  62221. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62222. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62223. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62224. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62225. }
  62226. else {
  62227. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62228. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62229. }
  62230. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62231. };
  62232. /**
  62233. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62234. * (eq to shadow prjection matrix * light transform matrix)
  62235. * @returns The transform matrix used to create the shadow map
  62236. */
  62237. ShadowGenerator.prototype.getTransformMatrix = function () {
  62238. var scene = this._scene;
  62239. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62240. return this._transformMatrix;
  62241. }
  62242. this._currentRenderID = scene.getRenderId();
  62243. this._currentFaceIndexCache = this._currentFaceIndex;
  62244. var lightPosition = this._light.position;
  62245. if (this._light.computeTransformedInformation()) {
  62246. lightPosition = this._light.transformedPosition;
  62247. }
  62248. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62249. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62250. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62251. }
  62252. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62253. this._cachedPosition.copyFrom(lightPosition);
  62254. this._cachedDirection.copyFrom(this._lightDirection);
  62255. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62256. var shadowMap = this.getShadowMap();
  62257. if (shadowMap) {
  62258. var renderList = shadowMap.renderList;
  62259. if (renderList) {
  62260. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62261. }
  62262. }
  62263. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62264. }
  62265. return this._transformMatrix;
  62266. };
  62267. /**
  62268. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62269. * Cube and 2D textures for instance.
  62270. */
  62271. ShadowGenerator.prototype.recreateShadowMap = function () {
  62272. var shadowMap = this._shadowMap;
  62273. if (!shadowMap) {
  62274. return;
  62275. }
  62276. // Track render list.
  62277. var renderList = shadowMap.renderList;
  62278. // Clean up existing data.
  62279. this._disposeRTTandPostProcesses();
  62280. // Reinitializes.
  62281. this._initializeGenerator();
  62282. // Reaffect the filter to ensure a correct fallback if necessary.
  62283. this.filter = this.filter;
  62284. // Reaffect the filter.
  62285. this._applyFilterValues();
  62286. // Reaffect Render List.
  62287. this._shadowMap.renderList = renderList;
  62288. };
  62289. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62290. if (this._shadowMap2) {
  62291. this._shadowMap2.dispose();
  62292. this._shadowMap2 = null;
  62293. }
  62294. if (this._boxBlurPostprocess) {
  62295. this._boxBlurPostprocess.dispose();
  62296. this._boxBlurPostprocess = null;
  62297. }
  62298. if (this._kernelBlurXPostprocess) {
  62299. this._kernelBlurXPostprocess.dispose();
  62300. this._kernelBlurXPostprocess = null;
  62301. }
  62302. if (this._kernelBlurYPostprocess) {
  62303. this._kernelBlurYPostprocess.dispose();
  62304. this._kernelBlurYPostprocess = null;
  62305. }
  62306. this._blurPostProcesses = [];
  62307. };
  62308. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62309. if (this._shadowMap) {
  62310. this._shadowMap.dispose();
  62311. this._shadowMap = null;
  62312. }
  62313. this._disposeBlurPostProcesses();
  62314. };
  62315. /**
  62316. * Disposes the ShadowGenerator.
  62317. * Returns nothing.
  62318. */
  62319. ShadowGenerator.prototype.dispose = function () {
  62320. this._disposeRTTandPostProcesses();
  62321. if (this._light) {
  62322. this._light._shadowGenerator = null;
  62323. this._light._markMeshesAsLightDirty();
  62324. }
  62325. };
  62326. /**
  62327. * Serializes the shadow generator setup to a json object.
  62328. * @returns The serialized JSON object
  62329. */
  62330. ShadowGenerator.prototype.serialize = function () {
  62331. var serializationObject = {};
  62332. var shadowMap = this.getShadowMap();
  62333. if (!shadowMap) {
  62334. return serializationObject;
  62335. }
  62336. serializationObject.lightId = this._light.id;
  62337. serializationObject.mapSize = shadowMap.getRenderSize();
  62338. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62339. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62340. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62341. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62342. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62343. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62344. serializationObject.depthScale = this.depthScale;
  62345. serializationObject.darkness = this.getDarkness();
  62346. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62347. serializationObject.blurKernel = this.blurKernel;
  62348. serializationObject.blurScale = this.blurScale;
  62349. serializationObject.useKernelBlur = this.useKernelBlur;
  62350. serializationObject.transparencyShadow = this._transparencyShadow;
  62351. serializationObject.bias = this.bias;
  62352. serializationObject.normalBias = this.normalBias;
  62353. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62354. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62355. serializationObject.filteringQuality = this.filteringQuality;
  62356. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62357. serializationObject.renderList = [];
  62358. if (shadowMap.renderList) {
  62359. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62360. var mesh = shadowMap.renderList[meshIndex];
  62361. serializationObject.renderList.push(mesh.id);
  62362. }
  62363. }
  62364. return serializationObject;
  62365. };
  62366. /**
  62367. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62368. * @param parsedShadowGenerator The JSON object to parse
  62369. * @param scene The scene to create the shadow map for
  62370. * @returns The parsed shadow generator
  62371. */
  62372. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62373. //casting to point light, as light is missing the position attr and typescript complains.
  62374. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62375. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62376. var shadowMap = shadowGenerator.getShadowMap();
  62377. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62378. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62379. meshes.forEach(function (mesh) {
  62380. if (!shadowMap) {
  62381. return;
  62382. }
  62383. if (!shadowMap.renderList) {
  62384. shadowMap.renderList = [];
  62385. }
  62386. shadowMap.renderList.push(mesh);
  62387. });
  62388. }
  62389. if (parsedShadowGenerator.usePoissonSampling) {
  62390. shadowGenerator.usePoissonSampling = true;
  62391. }
  62392. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62393. shadowGenerator.useExponentialShadowMap = true;
  62394. }
  62395. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62396. shadowGenerator.useBlurExponentialShadowMap = true;
  62397. }
  62398. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62399. shadowGenerator.useCloseExponentialShadowMap = true;
  62400. }
  62401. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62402. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62403. }
  62404. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62405. shadowGenerator.usePercentageCloserFiltering = true;
  62406. }
  62407. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62408. shadowGenerator.useContactHardeningShadow = true;
  62409. }
  62410. if (parsedShadowGenerator.filteringQuality) {
  62411. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62412. }
  62413. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62414. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62415. }
  62416. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62417. shadowGenerator.useExponentialShadowMap = true;
  62418. }
  62419. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62420. shadowGenerator.useBlurExponentialShadowMap = true;
  62421. }
  62422. if (parsedShadowGenerator.depthScale) {
  62423. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62424. }
  62425. if (parsedShadowGenerator.blurScale) {
  62426. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62427. }
  62428. if (parsedShadowGenerator.blurBoxOffset) {
  62429. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62430. }
  62431. if (parsedShadowGenerator.useKernelBlur) {
  62432. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62433. }
  62434. if (parsedShadowGenerator.blurKernel) {
  62435. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62436. }
  62437. if (parsedShadowGenerator.bias !== undefined) {
  62438. shadowGenerator.bias = parsedShadowGenerator.bias;
  62439. }
  62440. if (parsedShadowGenerator.normalBias !== undefined) {
  62441. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62442. }
  62443. if (parsedShadowGenerator.darkness) {
  62444. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62445. }
  62446. if (parsedShadowGenerator.transparencyShadow) {
  62447. shadowGenerator.setTransparencyShadow(true);
  62448. }
  62449. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62450. return shadowGenerator;
  62451. };
  62452. /**
  62453. * Shadow generator mode None: no filtering applied.
  62454. */
  62455. ShadowGenerator.FILTER_NONE = 0;
  62456. /**
  62457. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62458. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62459. */
  62460. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62461. /**
  62462. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62463. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62464. */
  62465. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62466. /**
  62467. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62468. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62469. */
  62470. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62471. /**
  62472. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62473. * edge artifacts on steep falloff.
  62474. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62475. */
  62476. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62477. /**
  62478. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62479. * edge artifacts on steep falloff.
  62480. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62481. */
  62482. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62483. /**
  62484. * Shadow generator mode PCF: Percentage Closer Filtering
  62485. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62486. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62487. */
  62488. ShadowGenerator.FILTER_PCF = 6;
  62489. /**
  62490. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62491. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62492. * Contact Hardening
  62493. */
  62494. ShadowGenerator.FILTER_PCSS = 7;
  62495. /**
  62496. * Reserved for PCF and PCSS
  62497. * Highest Quality.
  62498. *
  62499. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62500. *
  62501. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62502. */
  62503. ShadowGenerator.QUALITY_HIGH = 0;
  62504. /**
  62505. * Reserved for PCF and PCSS
  62506. * Good tradeoff for quality/perf cross devices
  62507. *
  62508. * Execute PCF on a 3*3 kernel.
  62509. *
  62510. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62511. */
  62512. ShadowGenerator.QUALITY_MEDIUM = 1;
  62513. /**
  62514. * Reserved for PCF and PCSS
  62515. * The lowest quality but the fastest.
  62516. *
  62517. * Execute PCF on a 1*1 kernel.
  62518. *
  62519. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62520. */
  62521. ShadowGenerator.QUALITY_LOW = 2;
  62522. return ShadowGenerator;
  62523. }());
  62524. BABYLON.ShadowGenerator = ShadowGenerator;
  62525. })(BABYLON || (BABYLON = {}));
  62526. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62527. "use strict";
  62528. var BABYLON;
  62529. (function (BABYLON) {
  62530. var DefaultLoadingScreen = /** @class */ (function () {
  62531. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62532. if (_loadingText === void 0) { _loadingText = ""; }
  62533. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62534. var _this = this;
  62535. this._renderingCanvas = _renderingCanvas;
  62536. this._loadingText = _loadingText;
  62537. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62538. // Resize
  62539. this._resizeLoadingUI = function () {
  62540. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62541. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62542. if (!_this._loadingDiv) {
  62543. return;
  62544. }
  62545. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62546. _this._loadingDiv.style.left = canvasRect.left + "px";
  62547. _this._loadingDiv.style.top = canvasRect.top + "px";
  62548. _this._loadingDiv.style.width = canvasRect.width + "px";
  62549. _this._loadingDiv.style.height = canvasRect.height + "px";
  62550. };
  62551. }
  62552. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62553. if (this._loadingDiv) {
  62554. // Do not add a loading screen if there is already one
  62555. return;
  62556. }
  62557. this._loadingDiv = document.createElement("div");
  62558. this._loadingDiv.id = "babylonjsLoadingDiv";
  62559. this._loadingDiv.style.opacity = "0";
  62560. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62561. this._loadingDiv.style.pointerEvents = "none";
  62562. // Loading text
  62563. this._loadingTextDiv = document.createElement("div");
  62564. this._loadingTextDiv.style.position = "absolute";
  62565. this._loadingTextDiv.style.left = "0";
  62566. this._loadingTextDiv.style.top = "50%";
  62567. this._loadingTextDiv.style.marginTop = "80px";
  62568. this._loadingTextDiv.style.width = "100%";
  62569. this._loadingTextDiv.style.height = "20px";
  62570. this._loadingTextDiv.style.fontFamily = "Arial";
  62571. this._loadingTextDiv.style.fontSize = "14px";
  62572. this._loadingTextDiv.style.color = "white";
  62573. this._loadingTextDiv.style.textAlign = "center";
  62574. this._loadingTextDiv.innerHTML = "Loading";
  62575. this._loadingDiv.appendChild(this._loadingTextDiv);
  62576. //set the predefined text
  62577. this._loadingTextDiv.innerHTML = this._loadingText;
  62578. // Generating keyframes
  62579. var style = document.createElement('style');
  62580. style.type = 'text/css';
  62581. 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 }";
  62582. style.innerHTML = keyFrames;
  62583. document.getElementsByTagName('head')[0].appendChild(style);
  62584. // Loading img
  62585. var imgBack = new Image();
  62586. 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";
  62587. imgBack.style.position = "absolute";
  62588. imgBack.style.left = "50%";
  62589. imgBack.style.top = "50%";
  62590. imgBack.style.marginLeft = "-60px";
  62591. imgBack.style.marginTop = "-60px";
  62592. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62593. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62594. imgBack.style.transformOrigin = "50% 50%";
  62595. imgBack.style.webkitTransformOrigin = "50% 50%";
  62596. this._loadingDiv.appendChild(imgBack);
  62597. this._resizeLoadingUI();
  62598. window.addEventListener("resize", this._resizeLoadingUI);
  62599. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62600. document.body.appendChild(this._loadingDiv);
  62601. this._loadingDiv.style.opacity = "1";
  62602. };
  62603. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62604. var _this = this;
  62605. if (!this._loadingDiv) {
  62606. return;
  62607. }
  62608. var onTransitionEnd = function () {
  62609. if (!_this._loadingDiv) {
  62610. return;
  62611. }
  62612. document.body.removeChild(_this._loadingDiv);
  62613. window.removeEventListener("resize", _this._resizeLoadingUI);
  62614. _this._loadingDiv = null;
  62615. };
  62616. this._loadingDiv.style.opacity = "0";
  62617. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62618. };
  62619. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62620. set: function (text) {
  62621. this._loadingText = text;
  62622. if (this._loadingTextDiv) {
  62623. this._loadingTextDiv.innerHTML = this._loadingText;
  62624. }
  62625. },
  62626. enumerable: true,
  62627. configurable: true
  62628. });
  62629. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62630. get: function () {
  62631. return this._loadingDivBackgroundColor;
  62632. },
  62633. set: function (color) {
  62634. this._loadingDivBackgroundColor = color;
  62635. if (!this._loadingDiv) {
  62636. return;
  62637. }
  62638. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62639. },
  62640. enumerable: true,
  62641. configurable: true
  62642. });
  62643. return DefaultLoadingScreen;
  62644. }());
  62645. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62646. })(BABYLON || (BABYLON = {}));
  62647. //# sourceMappingURL=babylon.loadingScreen.js.map
  62648. "use strict";
  62649. var BABYLON;
  62650. (function (BABYLON) {
  62651. var SceneLoaderProgressEvent = /** @class */ (function () {
  62652. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62653. this.lengthComputable = lengthComputable;
  62654. this.loaded = loaded;
  62655. this.total = total;
  62656. }
  62657. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62658. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62659. };
  62660. return SceneLoaderProgressEvent;
  62661. }());
  62662. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62663. var SceneLoader = /** @class */ (function () {
  62664. function SceneLoader() {
  62665. }
  62666. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62667. get: function () {
  62668. return 0;
  62669. },
  62670. enumerable: true,
  62671. configurable: true
  62672. });
  62673. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62674. get: function () {
  62675. return 1;
  62676. },
  62677. enumerable: true,
  62678. configurable: true
  62679. });
  62680. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62681. get: function () {
  62682. return 2;
  62683. },
  62684. enumerable: true,
  62685. configurable: true
  62686. });
  62687. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62688. get: function () {
  62689. return 3;
  62690. },
  62691. enumerable: true,
  62692. configurable: true
  62693. });
  62694. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62695. get: function () {
  62696. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62697. },
  62698. set: function (value) {
  62699. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62700. },
  62701. enumerable: true,
  62702. configurable: true
  62703. });
  62704. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62705. get: function () {
  62706. return SceneLoader._ShowLoadingScreen;
  62707. },
  62708. set: function (value) {
  62709. SceneLoader._ShowLoadingScreen = value;
  62710. },
  62711. enumerable: true,
  62712. configurable: true
  62713. });
  62714. Object.defineProperty(SceneLoader, "loggingLevel", {
  62715. get: function () {
  62716. return SceneLoader._loggingLevel;
  62717. },
  62718. set: function (value) {
  62719. SceneLoader._loggingLevel = value;
  62720. },
  62721. enumerable: true,
  62722. configurable: true
  62723. });
  62724. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62725. get: function () {
  62726. return SceneLoader._CleanBoneMatrixWeights;
  62727. },
  62728. set: function (value) {
  62729. SceneLoader._CleanBoneMatrixWeights = value;
  62730. },
  62731. enumerable: true,
  62732. configurable: true
  62733. });
  62734. SceneLoader._getDefaultPlugin = function () {
  62735. return SceneLoader._registeredPlugins[".babylon"];
  62736. };
  62737. SceneLoader._getPluginForExtension = function (extension) {
  62738. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62739. if (registeredPlugin) {
  62740. return registeredPlugin;
  62741. }
  62742. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62743. return SceneLoader._getDefaultPlugin();
  62744. };
  62745. SceneLoader._getPluginForDirectLoad = function (data) {
  62746. for (var extension in SceneLoader._registeredPlugins) {
  62747. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62748. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62749. return SceneLoader._registeredPlugins[extension];
  62750. }
  62751. }
  62752. return SceneLoader._getDefaultPlugin();
  62753. };
  62754. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62755. if (sceneFilename.name) {
  62756. sceneFilename = sceneFilename.name;
  62757. }
  62758. var queryStringPosition = sceneFilename.indexOf("?");
  62759. if (queryStringPosition !== -1) {
  62760. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62761. }
  62762. var dotPosition = sceneFilename.lastIndexOf(".");
  62763. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62764. return SceneLoader._getPluginForExtension(extension);
  62765. };
  62766. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62767. SceneLoader._getDirectLoad = function (sceneFilename) {
  62768. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62769. return sceneFilename.substr(5);
  62770. }
  62771. return null;
  62772. };
  62773. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62774. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62775. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62776. var plugin;
  62777. if (registeredPlugin.plugin.createPlugin) {
  62778. plugin = registeredPlugin.plugin.createPlugin();
  62779. }
  62780. else {
  62781. plugin = registeredPlugin.plugin;
  62782. }
  62783. var useArrayBuffer = registeredPlugin.isBinary;
  62784. var database;
  62785. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62786. var dataCallback = function (data, responseURL) {
  62787. if (scene.isDisposed) {
  62788. onError("Scene has been disposed");
  62789. return;
  62790. }
  62791. scene.database = database;
  62792. onSuccess(plugin, data, responseURL);
  62793. };
  62794. var request = null;
  62795. var pluginDisposed = false;
  62796. var onDisposeObservable = plugin.onDisposeObservable;
  62797. if (onDisposeObservable) {
  62798. onDisposeObservable.add(function () {
  62799. pluginDisposed = true;
  62800. if (request) {
  62801. request.abort();
  62802. request = null;
  62803. }
  62804. onDispose();
  62805. });
  62806. }
  62807. var manifestChecked = function () {
  62808. if (pluginDisposed) {
  62809. return;
  62810. }
  62811. var url = rootUrl + sceneFilename;
  62812. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62813. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62814. } : undefined, database, useArrayBuffer, function (request, exception) {
  62815. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62816. });
  62817. };
  62818. if (directLoad) {
  62819. dataCallback(directLoad);
  62820. return plugin;
  62821. }
  62822. if (rootUrl.indexOf("file:") === -1) {
  62823. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62824. if (canUseOfflineSupport) {
  62825. // Also check for exceptions
  62826. var exceptionFound = false;
  62827. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62828. var regex = _a[_i];
  62829. if (regex.test(rootUrl + sceneFilename)) {
  62830. exceptionFound = true;
  62831. break;
  62832. }
  62833. }
  62834. canUseOfflineSupport = !exceptionFound;
  62835. }
  62836. if (canUseOfflineSupport) {
  62837. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62838. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62839. }
  62840. else {
  62841. manifestChecked();
  62842. }
  62843. }
  62844. else {
  62845. var fileOrString = sceneFilename;
  62846. if (fileOrString.name) {
  62847. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62848. }
  62849. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62850. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62851. }
  62852. else {
  62853. onError("Unable to find file named " + sceneFilename);
  62854. }
  62855. }
  62856. return plugin;
  62857. };
  62858. // Public functions
  62859. SceneLoader.GetPluginForExtension = function (extension) {
  62860. return SceneLoader._getPluginForExtension(extension).plugin;
  62861. };
  62862. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62863. return !!SceneLoader._registeredPlugins[extension];
  62864. };
  62865. SceneLoader.RegisterPlugin = function (plugin) {
  62866. if (typeof plugin.extensions === "string") {
  62867. var extension = plugin.extensions;
  62868. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62869. plugin: plugin,
  62870. isBinary: false
  62871. };
  62872. }
  62873. else {
  62874. var extensions = plugin.extensions;
  62875. Object.keys(extensions).forEach(function (extension) {
  62876. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62877. plugin: plugin,
  62878. isBinary: extensions[extension].isBinary
  62879. };
  62880. });
  62881. }
  62882. };
  62883. /**
  62884. * Import meshes into a scene
  62885. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62886. * @param rootUrl a string that defines the root url for scene and resources
  62887. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62888. * @param scene the instance of BABYLON.Scene to append to
  62889. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62890. * @param onProgress a callback with a progress event for each file being loaded
  62891. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62892. * @param pluginExtension the extension used to determine the plugin
  62893. * @returns The loaded plugin
  62894. */
  62895. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62896. if (onSuccess === void 0) { onSuccess = null; }
  62897. if (onProgress === void 0) { onProgress = null; }
  62898. if (onError === void 0) { onError = null; }
  62899. if (pluginExtension === void 0) { pluginExtension = null; }
  62900. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62901. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62902. return null;
  62903. }
  62904. var loadingToken = {};
  62905. scene._addPendingData(loadingToken);
  62906. var disposeHandler = function () {
  62907. scene._removePendingData(loadingToken);
  62908. };
  62909. var errorHandler = function (message, exception) {
  62910. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62911. if (onError) {
  62912. onError(scene, errorMessage, exception);
  62913. }
  62914. else {
  62915. BABYLON.Tools.Error(errorMessage);
  62916. // should the exception be thrown?
  62917. }
  62918. disposeHandler();
  62919. };
  62920. var progressHandler = onProgress ? function (event) {
  62921. try {
  62922. onProgress(event);
  62923. }
  62924. catch (e) {
  62925. errorHandler("Error in onProgress callback", e);
  62926. }
  62927. } : undefined;
  62928. var successHandler = function (meshes, particleSystems, skeletons) {
  62929. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62930. if (onSuccess) {
  62931. try {
  62932. onSuccess(meshes, particleSystems, skeletons);
  62933. }
  62934. catch (e) {
  62935. errorHandler("Error in onSuccess callback", e);
  62936. }
  62937. }
  62938. scene._removePendingData(loadingToken);
  62939. };
  62940. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62941. if (plugin.rewriteRootURL) {
  62942. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62943. }
  62944. if (sceneFilename === "") {
  62945. if (sceneFilename === "") {
  62946. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62947. }
  62948. }
  62949. if (plugin.importMesh) {
  62950. var syncedPlugin = plugin;
  62951. var meshes = new Array();
  62952. var particleSystems = new Array();
  62953. var skeletons = new Array();
  62954. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62955. return;
  62956. }
  62957. scene.loadingPluginName = plugin.name;
  62958. successHandler(meshes, particleSystems, skeletons);
  62959. }
  62960. else {
  62961. var asyncedPlugin = plugin;
  62962. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62963. scene.loadingPluginName = plugin.name;
  62964. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62965. }).catch(function (error) {
  62966. errorHandler(error.message, error);
  62967. });
  62968. }
  62969. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62970. };
  62971. /**
  62972. * Import meshes into a scene
  62973. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62974. * @param rootUrl a string that defines the root url for scene and resources
  62975. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62976. * @param scene the instance of BABYLON.Scene to append to
  62977. * @param onProgress a callback with a progress event for each file being loaded
  62978. * @param pluginExtension the extension used to determine the plugin
  62979. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62980. */
  62981. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62982. if (onProgress === void 0) { onProgress = null; }
  62983. if (pluginExtension === void 0) { pluginExtension = null; }
  62984. return new Promise(function (resolve, reject) {
  62985. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62986. resolve({
  62987. meshes: meshes,
  62988. particleSystems: particleSystems,
  62989. skeletons: skeletons
  62990. });
  62991. }, onProgress, function (scene, message, exception) {
  62992. reject(exception || new Error(message));
  62993. });
  62994. });
  62995. };
  62996. /**
  62997. * Load a scene
  62998. * @param rootUrl a string that defines the root url for scene and resources
  62999. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63000. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63001. * @param onSuccess a callback with the scene when import succeeds
  63002. * @param onProgress a callback with a progress event for each file being loaded
  63003. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63004. * @param pluginExtension the extension used to determine the plugin
  63005. * @returns The loaded plugin
  63006. */
  63007. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  63008. if (onSuccess === void 0) { onSuccess = null; }
  63009. if (onProgress === void 0) { onProgress = null; }
  63010. if (onError === void 0) { onError = null; }
  63011. if (pluginExtension === void 0) { pluginExtension = null; }
  63012. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  63013. };
  63014. /**
  63015. * Load a scene
  63016. * @param rootUrl a string that defines the root url for scene and resources
  63017. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63018. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63019. * @param onProgress a callback with a progress event for each file being loaded
  63020. * @param pluginExtension the extension used to determine the plugin
  63021. * @returns The loaded scene
  63022. */
  63023. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  63024. if (onProgress === void 0) { onProgress = null; }
  63025. if (pluginExtension === void 0) { pluginExtension = null; }
  63026. return new Promise(function (resolve, reject) {
  63027. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  63028. resolve(scene);
  63029. }, onProgress, function (scene, message, exception) {
  63030. reject(exception || new Error(message));
  63031. }, pluginExtension);
  63032. });
  63033. };
  63034. /**
  63035. * Append a scene
  63036. * @param rootUrl a string that defines the root url for scene and resources
  63037. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63038. * @param scene is the instance of BABYLON.Scene to append to
  63039. * @param onSuccess a callback with the scene when import succeeds
  63040. * @param onProgress a callback with a progress event for each file being loaded
  63041. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63042. * @param pluginExtension the extension used to determine the plugin
  63043. * @returns The loaded plugin
  63044. */
  63045. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63046. if (onSuccess === void 0) { onSuccess = null; }
  63047. if (onProgress === void 0) { onProgress = null; }
  63048. if (onError === void 0) { onError = null; }
  63049. if (pluginExtension === void 0) { pluginExtension = null; }
  63050. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63051. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63052. return null;
  63053. }
  63054. if (SceneLoader.ShowLoadingScreen) {
  63055. scene.getEngine().displayLoadingUI();
  63056. }
  63057. var loadingToken = {};
  63058. scene._addPendingData(loadingToken);
  63059. var disposeHandler = function () {
  63060. scene._removePendingData(loadingToken);
  63061. scene.getEngine().hideLoadingUI();
  63062. };
  63063. var errorHandler = function (message, exception) {
  63064. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63065. if (onError) {
  63066. onError(scene, errorMessage, exception);
  63067. }
  63068. else {
  63069. BABYLON.Tools.Error(errorMessage);
  63070. // should the exception be thrown?
  63071. }
  63072. disposeHandler();
  63073. };
  63074. var progressHandler = onProgress ? function (event) {
  63075. try {
  63076. onProgress(event);
  63077. }
  63078. catch (e) {
  63079. errorHandler("Error in onProgress callback", e);
  63080. }
  63081. } : undefined;
  63082. var successHandler = function () {
  63083. if (onSuccess) {
  63084. try {
  63085. onSuccess(scene);
  63086. }
  63087. catch (e) {
  63088. errorHandler("Error in onSuccess callback", e);
  63089. }
  63090. }
  63091. scene._removePendingData(loadingToken);
  63092. };
  63093. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63094. if (sceneFilename === "") {
  63095. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63096. }
  63097. if (plugin.load) {
  63098. var syncedPlugin = plugin;
  63099. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63100. return;
  63101. }
  63102. scene.loadingPluginName = plugin.name;
  63103. successHandler();
  63104. }
  63105. else {
  63106. var asyncedPlugin = plugin;
  63107. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63108. scene.loadingPluginName = plugin.name;
  63109. successHandler();
  63110. }).catch(function (error) {
  63111. errorHandler(error.message, error);
  63112. });
  63113. }
  63114. if (SceneLoader.ShowLoadingScreen) {
  63115. scene.executeWhenReady(function () {
  63116. scene.getEngine().hideLoadingUI();
  63117. });
  63118. }
  63119. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63120. };
  63121. /**
  63122. * Append a scene
  63123. * @param rootUrl a string that defines the root url for scene and resources
  63124. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63125. * @param scene is the instance of BABYLON.Scene to append to
  63126. * @param onProgress a callback with a progress event for each file being loaded
  63127. * @param pluginExtension the extension used to determine the plugin
  63128. * @returns The given scene
  63129. */
  63130. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63131. if (onProgress === void 0) { onProgress = null; }
  63132. if (pluginExtension === void 0) { pluginExtension = null; }
  63133. return new Promise(function (resolve, reject) {
  63134. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63135. resolve(scene);
  63136. }, onProgress, function (scene, message, exception) {
  63137. reject(exception || new Error(message));
  63138. }, pluginExtension);
  63139. });
  63140. };
  63141. /**
  63142. * Load a scene into an asset container
  63143. * @param rootUrl a string that defines the root url for scene and resources
  63144. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63145. * @param scene is the instance of BABYLON.Scene to append to
  63146. * @param onSuccess a callback with the scene when import succeeds
  63147. * @param onProgress a callback with a progress event for each file being loaded
  63148. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63149. * @param pluginExtension the extension used to determine the plugin
  63150. * @returns The loaded plugin
  63151. */
  63152. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63153. if (onSuccess === void 0) { onSuccess = null; }
  63154. if (onProgress === void 0) { onProgress = null; }
  63155. if (onError === void 0) { onError = null; }
  63156. if (pluginExtension === void 0) { pluginExtension = null; }
  63157. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63158. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63159. return null;
  63160. }
  63161. var loadingToken = {};
  63162. scene._addPendingData(loadingToken);
  63163. var disposeHandler = function () {
  63164. scene._removePendingData(loadingToken);
  63165. };
  63166. var errorHandler = function (message, exception) {
  63167. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63168. if (onError) {
  63169. onError(scene, errorMessage, exception);
  63170. }
  63171. else {
  63172. BABYLON.Tools.Error(errorMessage);
  63173. // should the exception be thrown?
  63174. }
  63175. disposeHandler();
  63176. };
  63177. var progressHandler = onProgress ? function (event) {
  63178. try {
  63179. onProgress(event);
  63180. }
  63181. catch (e) {
  63182. errorHandler("Error in onProgress callback", e);
  63183. }
  63184. } : undefined;
  63185. var successHandler = function (assets) {
  63186. if (onSuccess) {
  63187. try {
  63188. onSuccess(assets);
  63189. }
  63190. catch (e) {
  63191. errorHandler("Error in onSuccess callback", e);
  63192. }
  63193. }
  63194. scene._removePendingData(loadingToken);
  63195. };
  63196. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63197. if (plugin.loadAssetContainer) {
  63198. var syncedPlugin = plugin;
  63199. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63200. if (!assetContainer) {
  63201. return;
  63202. }
  63203. scene.loadingPluginName = plugin.name;
  63204. successHandler(assetContainer);
  63205. }
  63206. else if (plugin.loadAssetContainerAsync) {
  63207. var asyncedPlugin = plugin;
  63208. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63209. scene.loadingPluginName = plugin.name;
  63210. successHandler(assetContainer);
  63211. }).catch(function (error) {
  63212. errorHandler(error.message, error);
  63213. });
  63214. }
  63215. else {
  63216. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63217. }
  63218. if (SceneLoader.ShowLoadingScreen) {
  63219. scene.executeWhenReady(function () {
  63220. scene.getEngine().hideLoadingUI();
  63221. });
  63222. }
  63223. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63224. };
  63225. /**
  63226. * Load a scene into an asset container
  63227. * @param rootUrl a string that defines the root url for scene and resources
  63228. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63229. * @param scene is the instance of BABYLON.Scene to append to
  63230. * @param onProgress a callback with a progress event for each file being loaded
  63231. * @param pluginExtension the extension used to determine the plugin
  63232. * @returns The loaded asset container
  63233. */
  63234. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63235. if (onProgress === void 0) { onProgress = null; }
  63236. if (pluginExtension === void 0) { pluginExtension = null; }
  63237. return new Promise(function (resolve, reject) {
  63238. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63239. resolve(assetContainer);
  63240. }, onProgress, function (scene, message, exception) {
  63241. reject(exception || new Error(message));
  63242. }, pluginExtension);
  63243. });
  63244. };
  63245. // Flags
  63246. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63247. SceneLoader._ShowLoadingScreen = true;
  63248. SceneLoader._CleanBoneMatrixWeights = false;
  63249. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63250. // Members
  63251. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63252. SceneLoader._registeredPlugins = {};
  63253. return SceneLoader;
  63254. }());
  63255. BABYLON.SceneLoader = SceneLoader;
  63256. ;
  63257. })(BABYLON || (BABYLON = {}));
  63258. //# sourceMappingURL=babylon.sceneLoader.js.map
  63259. "use strict";
  63260. var BABYLON;
  63261. (function (BABYLON) {
  63262. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63263. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63264. var parsedMaterial = parsedData.materials[index];
  63265. if (parsedMaterial.id === id) {
  63266. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63267. }
  63268. }
  63269. return null;
  63270. };
  63271. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63272. for (var i in names) {
  63273. if (mesh.name === names[i]) {
  63274. hierarchyIds.push(mesh.id);
  63275. return true;
  63276. }
  63277. }
  63278. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63279. hierarchyIds.push(mesh.id);
  63280. return true;
  63281. }
  63282. return false;
  63283. };
  63284. var logOperation = function (operation, producer) {
  63285. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63286. };
  63287. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63288. if (addToScene === void 0) { addToScene = false; }
  63289. var container = new BABYLON.AssetContainer(scene);
  63290. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63291. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63292. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63293. // and avoid problems with multiple concurrent .babylon loads.
  63294. var log = "importScene has failed JSON parse";
  63295. try {
  63296. var parsedData = JSON.parse(data);
  63297. log = "";
  63298. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63299. var index;
  63300. var cache;
  63301. // Lights
  63302. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63303. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63304. var parsedLight = parsedData.lights[index];
  63305. var light = BABYLON.Light.Parse(parsedLight, scene);
  63306. if (light) {
  63307. container.lights.push(light);
  63308. log += (index === 0 ? "\n\tLights:" : "");
  63309. log += "\n\t\t" + light.toString(fullDetails);
  63310. }
  63311. }
  63312. }
  63313. // Animations
  63314. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63315. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63316. var parsedAnimation = parsedData.animations[index];
  63317. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63318. scene.animations.push(animation);
  63319. container.animations.push(animation);
  63320. log += (index === 0 ? "\n\tAnimations:" : "");
  63321. log += "\n\t\t" + animation.toString(fullDetails);
  63322. }
  63323. }
  63324. // Materials
  63325. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63326. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63327. var parsedMaterial = parsedData.materials[index];
  63328. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63329. container.materials.push(mat);
  63330. log += (index === 0 ? "\n\tMaterials:" : "");
  63331. log += "\n\t\t" + mat.toString(fullDetails);
  63332. }
  63333. }
  63334. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63335. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63336. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63337. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63338. container.multiMaterials.push(mmat);
  63339. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63340. log += "\n\t\t" + mmat.toString(fullDetails);
  63341. }
  63342. }
  63343. // Morph targets
  63344. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63345. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63346. var managerData = _a[_i];
  63347. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63348. }
  63349. }
  63350. // Skeletons
  63351. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63352. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63353. var parsedSkeleton = parsedData.skeletons[index];
  63354. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63355. container.skeletons.push(skeleton);
  63356. log += (index === 0 ? "\n\tSkeletons:" : "");
  63357. log += "\n\t\t" + skeleton.toString(fullDetails);
  63358. }
  63359. }
  63360. // Geometries
  63361. var geometries = parsedData.geometries;
  63362. if (geometries !== undefined && geometries !== null) {
  63363. var addedGeometry = new Array();
  63364. // Boxes
  63365. var boxes = geometries.boxes;
  63366. if (boxes !== undefined && boxes !== null) {
  63367. for (index = 0, cache = boxes.length; index < cache; index++) {
  63368. var parsedBox = boxes[index];
  63369. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63370. }
  63371. }
  63372. // Spheres
  63373. var spheres = geometries.spheres;
  63374. if (spheres !== undefined && spheres !== null) {
  63375. for (index = 0, cache = spheres.length; index < cache; index++) {
  63376. var parsedSphere = spheres[index];
  63377. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63378. }
  63379. }
  63380. // Cylinders
  63381. var cylinders = geometries.cylinders;
  63382. if (cylinders !== undefined && cylinders !== null) {
  63383. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63384. var parsedCylinder = cylinders[index];
  63385. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63386. }
  63387. }
  63388. // Toruses
  63389. var toruses = geometries.toruses;
  63390. if (toruses !== undefined && toruses !== null) {
  63391. for (index = 0, cache = toruses.length; index < cache; index++) {
  63392. var parsedTorus = toruses[index];
  63393. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63394. }
  63395. }
  63396. // Grounds
  63397. var grounds = geometries.grounds;
  63398. if (grounds !== undefined && grounds !== null) {
  63399. for (index = 0, cache = grounds.length; index < cache; index++) {
  63400. var parsedGround = grounds[index];
  63401. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63402. }
  63403. }
  63404. // Planes
  63405. var planes = geometries.planes;
  63406. if (planes !== undefined && planes !== null) {
  63407. for (index = 0, cache = planes.length; index < cache; index++) {
  63408. var parsedPlane = planes[index];
  63409. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63410. }
  63411. }
  63412. // TorusKnots
  63413. var torusKnots = geometries.torusKnots;
  63414. if (torusKnots !== undefined && torusKnots !== null) {
  63415. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63416. var parsedTorusKnot = torusKnots[index];
  63417. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63418. }
  63419. }
  63420. // VertexData
  63421. var vertexData = geometries.vertexData;
  63422. if (vertexData !== undefined && vertexData !== null) {
  63423. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63424. var parsedVertexData = vertexData[index];
  63425. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63426. }
  63427. }
  63428. addedGeometry.forEach(function (g) {
  63429. if (g) {
  63430. container.geometries.push(g);
  63431. }
  63432. });
  63433. }
  63434. // Transform nodes
  63435. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63436. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63437. var parsedTransformNode = parsedData.transformNodes[index];
  63438. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63439. container.transformNodes.push(node);
  63440. }
  63441. }
  63442. // Meshes
  63443. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63444. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63445. var parsedMesh = parsedData.meshes[index];
  63446. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63447. container.meshes.push(mesh);
  63448. log += (index === 0 ? "\n\tMeshes:" : "");
  63449. log += "\n\t\t" + mesh.toString(fullDetails);
  63450. }
  63451. }
  63452. // Cameras
  63453. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63454. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63455. var parsedCamera = parsedData.cameras[index];
  63456. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63457. container.cameras.push(camera);
  63458. log += (index === 0 ? "\n\tCameras:" : "");
  63459. log += "\n\t\t" + camera.toString(fullDetails);
  63460. }
  63461. }
  63462. // Browsing all the graph to connect the dots
  63463. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63464. var camera = scene.cameras[index];
  63465. if (camera._waitingParentId) {
  63466. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63467. camera._waitingParentId = null;
  63468. }
  63469. }
  63470. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63471. var light_1 = scene.lights[index];
  63472. if (light_1 && light_1._waitingParentId) {
  63473. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63474. light_1._waitingParentId = null;
  63475. }
  63476. }
  63477. // Sounds
  63478. // TODO: add sound
  63479. var loadedSounds = [];
  63480. var loadedSound;
  63481. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63482. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63483. var parsedSound = parsedData.sounds[index];
  63484. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63485. if (!parsedSound.url)
  63486. parsedSound.url = parsedSound.name;
  63487. if (!loadedSounds[parsedSound.url]) {
  63488. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63489. loadedSounds[parsedSound.url] = loadedSound;
  63490. container.sounds.push(loadedSound);
  63491. }
  63492. else {
  63493. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63494. }
  63495. }
  63496. else {
  63497. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63498. }
  63499. }
  63500. }
  63501. loadedSounds = [];
  63502. // Connect parents & children and parse actions
  63503. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63504. var transformNode = scene.transformNodes[index];
  63505. if (transformNode._waitingParentId) {
  63506. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63507. transformNode._waitingParentId = null;
  63508. }
  63509. }
  63510. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63511. var mesh = scene.meshes[index];
  63512. if (mesh._waitingParentId) {
  63513. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63514. mesh._waitingParentId = null;
  63515. }
  63516. if (mesh._waitingActions) {
  63517. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63518. mesh._waitingActions = null;
  63519. }
  63520. }
  63521. // freeze world matrix application
  63522. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63523. var currentMesh = scene.meshes[index];
  63524. if (currentMesh._waitingFreezeWorldMatrix) {
  63525. currentMesh.freezeWorldMatrix();
  63526. currentMesh._waitingFreezeWorldMatrix = null;
  63527. }
  63528. else {
  63529. currentMesh.computeWorldMatrix(true);
  63530. }
  63531. }
  63532. // Particles Systems
  63533. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63534. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63535. var parsedParticleSystem = parsedData.particleSystems[index];
  63536. if (parsedParticleSystem.activeParticleCount) {
  63537. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63538. container.particleSystems.push(ps);
  63539. }
  63540. else {
  63541. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63542. container.particleSystems.push(ps);
  63543. }
  63544. }
  63545. }
  63546. // Lens flares
  63547. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63548. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63549. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63550. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63551. container.lensFlareSystems.push(lf);
  63552. }
  63553. }
  63554. // Shadows
  63555. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63556. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63557. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63558. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63559. container.shadowGenerators.push(sg);
  63560. }
  63561. }
  63562. // Lights exclusions / inclusions
  63563. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63564. var light_2 = scene.lights[index];
  63565. // Excluded check
  63566. if (light_2._excludedMeshesIds.length > 0) {
  63567. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63568. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63569. if (excludedMesh) {
  63570. light_2.excludedMeshes.push(excludedMesh);
  63571. }
  63572. }
  63573. light_2._excludedMeshesIds = [];
  63574. }
  63575. // Included check
  63576. if (light_2._includedOnlyMeshesIds.length > 0) {
  63577. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63578. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63579. if (includedOnlyMesh) {
  63580. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63581. }
  63582. }
  63583. light_2._includedOnlyMeshesIds = [];
  63584. }
  63585. }
  63586. // Actions (scene)
  63587. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63588. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63589. }
  63590. if (!addToScene) {
  63591. container.removeAllFromScene();
  63592. }
  63593. }
  63594. catch (err) {
  63595. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63596. if (onError) {
  63597. onError(msg, err);
  63598. }
  63599. else {
  63600. BABYLON.Tools.Log(msg);
  63601. throw err;
  63602. }
  63603. }
  63604. finally {
  63605. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63606. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63607. }
  63608. }
  63609. return container;
  63610. };
  63611. BABYLON.SceneLoader.RegisterPlugin({
  63612. name: "babylon.js",
  63613. extensions: ".babylon",
  63614. canDirectLoad: function (data) {
  63615. if (data.indexOf("babylon") !== -1) {
  63616. return true;
  63617. }
  63618. return false;
  63619. },
  63620. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63621. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63622. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63623. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63624. // and avoid problems with multiple concurrent .babylon loads.
  63625. var log = "importMesh has failed JSON parse";
  63626. try {
  63627. var parsedData = JSON.parse(data);
  63628. log = "";
  63629. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63630. if (!meshesNames) {
  63631. meshesNames = null;
  63632. }
  63633. else if (!Array.isArray(meshesNames)) {
  63634. meshesNames = [meshesNames];
  63635. }
  63636. var hierarchyIds = new Array();
  63637. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63638. var loadedSkeletonsIds = [];
  63639. var loadedMaterialsIds = [];
  63640. var index;
  63641. var cache;
  63642. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63643. var parsedMesh = parsedData.meshes[index];
  63644. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63645. if (meshesNames !== null) {
  63646. // Remove found mesh name from list.
  63647. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63648. }
  63649. //Geometry?
  63650. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63651. //does the file contain geometries?
  63652. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63653. //find the correct geometry and add it to the scene
  63654. var found = false;
  63655. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63656. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63657. return;
  63658. }
  63659. else {
  63660. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63661. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63662. switch (geometryType) {
  63663. case "boxes":
  63664. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63665. break;
  63666. case "spheres":
  63667. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63668. break;
  63669. case "cylinders":
  63670. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63671. break;
  63672. case "toruses":
  63673. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63674. break;
  63675. case "grounds":
  63676. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63677. break;
  63678. case "planes":
  63679. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63680. break;
  63681. case "torusKnots":
  63682. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63683. break;
  63684. case "vertexData":
  63685. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63686. break;
  63687. }
  63688. found = true;
  63689. }
  63690. });
  63691. }
  63692. });
  63693. if (found === false) {
  63694. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63695. }
  63696. }
  63697. }
  63698. // Material ?
  63699. if (parsedMesh.materialId) {
  63700. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63701. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63702. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63703. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63704. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63705. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63706. var subMatId = parsedMultiMaterial.materials[matIndex];
  63707. loadedMaterialsIds.push(subMatId);
  63708. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63709. if (mat) {
  63710. log += "\n\tMaterial " + mat.toString(fullDetails);
  63711. }
  63712. }
  63713. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63714. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63715. if (mmat) {
  63716. materialFound = true;
  63717. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63718. }
  63719. break;
  63720. }
  63721. }
  63722. }
  63723. if (materialFound === false) {
  63724. loadedMaterialsIds.push(parsedMesh.materialId);
  63725. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63726. if (!mat) {
  63727. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63728. }
  63729. else {
  63730. log += "\n\tMaterial " + mat.toString(fullDetails);
  63731. }
  63732. }
  63733. }
  63734. // Skeleton ?
  63735. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63736. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63737. if (skeletonAlreadyLoaded === false) {
  63738. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63739. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63740. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63741. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63742. skeletons.push(skeleton);
  63743. loadedSkeletonsIds.push(parsedSkeleton.id);
  63744. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63745. }
  63746. }
  63747. }
  63748. }
  63749. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63750. meshes.push(mesh);
  63751. log += "\n\tMesh " + mesh.toString(fullDetails);
  63752. }
  63753. }
  63754. // Connecting parents
  63755. var currentMesh;
  63756. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63757. currentMesh = scene.meshes[index];
  63758. if (currentMesh._waitingParentId) {
  63759. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63760. currentMesh._waitingParentId = null;
  63761. }
  63762. }
  63763. // freeze and compute world matrix application
  63764. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63765. currentMesh = scene.meshes[index];
  63766. if (currentMesh._waitingFreezeWorldMatrix) {
  63767. currentMesh.freezeWorldMatrix();
  63768. currentMesh._waitingFreezeWorldMatrix = null;
  63769. }
  63770. else {
  63771. currentMesh.computeWorldMatrix(true);
  63772. }
  63773. }
  63774. }
  63775. // Particles
  63776. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63777. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63778. var parsedParticleSystem = parsedData.particleSystems[index];
  63779. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63780. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63781. }
  63782. }
  63783. }
  63784. return true;
  63785. }
  63786. catch (err) {
  63787. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63788. if (onError) {
  63789. onError(msg, err);
  63790. }
  63791. else {
  63792. BABYLON.Tools.Log(msg);
  63793. throw err;
  63794. }
  63795. }
  63796. finally {
  63797. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63798. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63799. }
  63800. }
  63801. return false;
  63802. },
  63803. load: function (scene, data, rootUrl, onError) {
  63804. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63805. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63806. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63807. // and avoid problems with multiple concurrent .babylon loads.
  63808. var log = "importScene has failed JSON parse";
  63809. try {
  63810. var parsedData = JSON.parse(data);
  63811. log = "";
  63812. // Scene
  63813. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63814. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63815. }
  63816. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63817. scene.autoClear = parsedData.autoClear;
  63818. }
  63819. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63820. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63821. }
  63822. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63823. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63824. }
  63825. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63826. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63827. }
  63828. // Fog
  63829. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63830. scene.fogMode = parsedData.fogMode;
  63831. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63832. scene.fogStart = parsedData.fogStart;
  63833. scene.fogEnd = parsedData.fogEnd;
  63834. scene.fogDensity = parsedData.fogDensity;
  63835. log += "\tFog mode for scene: ";
  63836. switch (scene.fogMode) {
  63837. // getters not compiling, so using hardcoded
  63838. case 1:
  63839. log += "exp\n";
  63840. break;
  63841. case 2:
  63842. log += "exp2\n";
  63843. break;
  63844. case 3:
  63845. log += "linear\n";
  63846. break;
  63847. }
  63848. }
  63849. //Physics
  63850. if (parsedData.physicsEnabled) {
  63851. var physicsPlugin;
  63852. if (parsedData.physicsEngine === "cannon") {
  63853. physicsPlugin = new BABYLON.CannonJSPlugin();
  63854. }
  63855. else if (parsedData.physicsEngine === "oimo") {
  63856. physicsPlugin = new BABYLON.OimoJSPlugin();
  63857. }
  63858. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63859. //else - default engine, which is currently oimo
  63860. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63861. scene.enablePhysics(physicsGravity, physicsPlugin);
  63862. }
  63863. // Metadata
  63864. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63865. scene.metadata = parsedData.metadata;
  63866. }
  63867. //collisions, if defined. otherwise, default is true
  63868. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63869. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63870. }
  63871. scene.workerCollisions = !!parsedData.workerCollisions;
  63872. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63873. if (!container) {
  63874. return false;
  63875. }
  63876. if (parsedData.autoAnimate) {
  63877. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63878. }
  63879. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63880. scene.setActiveCameraByID(parsedData.activeCameraID);
  63881. }
  63882. // Environment texture
  63883. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63884. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63885. if (parsedData.createDefaultSkybox === true) {
  63886. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63887. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63888. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63889. }
  63890. }
  63891. // Finish
  63892. return true;
  63893. }
  63894. catch (err) {
  63895. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63896. if (onError) {
  63897. onError(msg, err);
  63898. }
  63899. else {
  63900. BABYLON.Tools.Log(msg);
  63901. throw err;
  63902. }
  63903. }
  63904. finally {
  63905. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63906. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63907. }
  63908. }
  63909. return false;
  63910. },
  63911. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63912. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63913. return container;
  63914. }
  63915. });
  63916. })(BABYLON || (BABYLON = {}));
  63917. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63918. "use strict";
  63919. var BABYLON;
  63920. (function (BABYLON) {
  63921. var FilesInput = /** @class */ (function () {
  63922. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63923. this.onProcessFileCallback = function () { return true; };
  63924. this._engine = engine;
  63925. this._currentScene = scene;
  63926. this._sceneLoadedCallback = sceneLoadedCallback;
  63927. this._progressCallback = progressCallback;
  63928. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63929. this._textureLoadingCallback = textureLoadingCallback;
  63930. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63931. this._onReloadCallback = onReloadCallback;
  63932. this._errorCallback = errorCallback;
  63933. }
  63934. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63935. var _this = this;
  63936. if (elementToMonitor) {
  63937. this._elementToMonitor = elementToMonitor;
  63938. this._dragEnterHandler = function (e) { _this.drag(e); };
  63939. this._dragOverHandler = function (e) { _this.drag(e); };
  63940. this._dropHandler = function (e) { _this.drop(e); };
  63941. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63942. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63943. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63944. }
  63945. };
  63946. FilesInput.prototype.dispose = function () {
  63947. if (!this._elementToMonitor) {
  63948. return;
  63949. }
  63950. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63951. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63952. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63953. };
  63954. FilesInput.prototype.renderFunction = function () {
  63955. if (this._additionalRenderLoopLogicCallback) {
  63956. this._additionalRenderLoopLogicCallback();
  63957. }
  63958. if (this._currentScene) {
  63959. if (this._textureLoadingCallback) {
  63960. var remaining = this._currentScene.getWaitingItemsCount();
  63961. if (remaining > 0) {
  63962. this._textureLoadingCallback(remaining);
  63963. }
  63964. }
  63965. this._currentScene.render();
  63966. }
  63967. };
  63968. FilesInput.prototype.drag = function (e) {
  63969. e.stopPropagation();
  63970. e.preventDefault();
  63971. };
  63972. FilesInput.prototype.drop = function (eventDrop) {
  63973. eventDrop.stopPropagation();
  63974. eventDrop.preventDefault();
  63975. this.loadFiles(eventDrop);
  63976. };
  63977. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63978. var _this = this;
  63979. var reader = folder.createReader();
  63980. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63981. reader.readEntries(function (entries) {
  63982. remaining.count += entries.length;
  63983. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63984. var entry = entries_1[_i];
  63985. if (entry.isFile) {
  63986. entry.file(function (file) {
  63987. file.correctName = relativePath + file.name;
  63988. files.push(file);
  63989. if (--remaining.count === 0) {
  63990. callback();
  63991. }
  63992. });
  63993. }
  63994. else if (entry.isDirectory) {
  63995. _this._traverseFolder(entry, files, remaining, callback);
  63996. }
  63997. }
  63998. if (--remaining.count) {
  63999. callback();
  64000. }
  64001. });
  64002. };
  64003. FilesInput.prototype._processFiles = function (files) {
  64004. for (var i = 0; i < files.length; i++) {
  64005. var name = files[i].correctName.toLowerCase();
  64006. var extension = name.split('.').pop();
  64007. if (!this.onProcessFileCallback(files[i], name, extension)) {
  64008. continue;
  64009. }
  64010. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  64011. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  64012. this._sceneFileToLoad = files[i];
  64013. }
  64014. else {
  64015. FilesInput.FilesToLoad[name] = files[i];
  64016. }
  64017. }
  64018. };
  64019. FilesInput.prototype.loadFiles = function (event) {
  64020. var _this = this;
  64021. if (this._startingProcessingFilesCallback)
  64022. this._startingProcessingFilesCallback();
  64023. // Handling data transfer via drag'n'drop
  64024. if (event && event.dataTransfer && event.dataTransfer.files) {
  64025. this._filesToLoad = event.dataTransfer.files;
  64026. }
  64027. // Handling files from input files
  64028. if (event && event.target && event.target.files) {
  64029. this._filesToLoad = event.target.files;
  64030. }
  64031. if (this._filesToLoad && this._filesToLoad.length > 0) {
  64032. var files_1 = new Array();
  64033. var folders = [];
  64034. var items = event.dataTransfer ? event.dataTransfer.items : null;
  64035. for (var i = 0; i < this._filesToLoad.length; i++) {
  64036. var fileToLoad = this._filesToLoad[i];
  64037. var name_1 = fileToLoad.name.toLowerCase();
  64038. var entry = void 0;
  64039. fileToLoad.correctName = name_1;
  64040. if (items) {
  64041. var item = items[i];
  64042. if (item.getAsEntry) {
  64043. entry = item.getAsEntry();
  64044. }
  64045. else if (item.webkitGetAsEntry) {
  64046. entry = item.webkitGetAsEntry();
  64047. }
  64048. }
  64049. if (!entry) {
  64050. files_1.push(fileToLoad);
  64051. }
  64052. else {
  64053. if (entry.isDirectory) {
  64054. folders.push(entry);
  64055. }
  64056. else {
  64057. files_1.push(fileToLoad);
  64058. }
  64059. }
  64060. }
  64061. if (folders.length === 0) {
  64062. this._processFiles(files_1);
  64063. this._processReload();
  64064. }
  64065. else {
  64066. var remaining = { count: folders.length };
  64067. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64068. var folder = folders_1[_i];
  64069. this._traverseFolder(folder, files_1, remaining, function () {
  64070. _this._processFiles(files_1);
  64071. if (remaining.count === 0) {
  64072. _this._processReload();
  64073. }
  64074. });
  64075. }
  64076. }
  64077. }
  64078. };
  64079. FilesInput.prototype._processReload = function () {
  64080. if (this._onReloadCallback) {
  64081. this._onReloadCallback(this._sceneFileToLoad);
  64082. }
  64083. else {
  64084. this.reload();
  64085. }
  64086. };
  64087. FilesInput.prototype.reload = function () {
  64088. var _this = this;
  64089. // If a scene file has been provided
  64090. if (this._sceneFileToLoad) {
  64091. if (this._currentScene) {
  64092. if (BABYLON.Tools.errorsCount > 0) {
  64093. BABYLON.Tools.ClearLogCache();
  64094. }
  64095. this._engine.stopRenderLoop();
  64096. this._currentScene.dispose();
  64097. }
  64098. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64099. if (_this._progressCallback) {
  64100. _this._progressCallback(progress);
  64101. }
  64102. }).then(function (scene) {
  64103. _this._currentScene = scene;
  64104. if (_this._sceneLoadedCallback) {
  64105. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64106. }
  64107. // Wait for textures and shaders to be ready
  64108. _this._currentScene.executeWhenReady(function () {
  64109. _this._engine.runRenderLoop(function () {
  64110. _this.renderFunction();
  64111. });
  64112. });
  64113. }).catch(function (error) {
  64114. if (_this._errorCallback) {
  64115. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64116. }
  64117. });
  64118. }
  64119. else {
  64120. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64121. }
  64122. };
  64123. FilesInput.FilesToLoad = {};
  64124. return FilesInput;
  64125. }());
  64126. BABYLON.FilesInput = FilesInput;
  64127. })(BABYLON || (BABYLON = {}));
  64128. //# sourceMappingURL=babylon.filesInput.js.map
  64129. "use strict";
  64130. var BABYLON;
  64131. (function (BABYLON) {
  64132. /**
  64133. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64134. * The underlying implementation relies on an associative array to ensure the best performances.
  64135. * The value can be anything including 'null' but except 'undefined'
  64136. */
  64137. var StringDictionary = /** @class */ (function () {
  64138. function StringDictionary() {
  64139. this._count = 0;
  64140. this._data = {};
  64141. }
  64142. /**
  64143. * This will clear this dictionary and copy the content from the 'source' one.
  64144. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64145. * @param source the dictionary to take the content from and copy to this dictionary
  64146. */
  64147. StringDictionary.prototype.copyFrom = function (source) {
  64148. var _this = this;
  64149. this.clear();
  64150. source.forEach(function (t, v) { return _this.add(t, v); });
  64151. };
  64152. /**
  64153. * Get a value based from its key
  64154. * @param key the given key to get the matching value from
  64155. * @return the value if found, otherwise undefined is returned
  64156. */
  64157. StringDictionary.prototype.get = function (key) {
  64158. var val = this._data[key];
  64159. if (val !== undefined) {
  64160. return val;
  64161. }
  64162. return undefined;
  64163. };
  64164. /**
  64165. * Get a value from its key or add it if it doesn't exist.
  64166. * This method will ensure you that a given key/data will be present in the dictionary.
  64167. * @param key the given key to get the matching value from
  64168. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64169. * The factory will only be invoked if there's no data for the given key.
  64170. * @return the value corresponding to the key.
  64171. */
  64172. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64173. var val = this.get(key);
  64174. if (val !== undefined) {
  64175. return val;
  64176. }
  64177. val = factory(key);
  64178. if (val) {
  64179. this.add(key, val);
  64180. }
  64181. return val;
  64182. };
  64183. /**
  64184. * Get a value from its key if present in the dictionary otherwise add it
  64185. * @param key the key to get the value from
  64186. * @param val if there's no such key/value pair in the dictionary add it with this value
  64187. * @return the value corresponding to the key
  64188. */
  64189. StringDictionary.prototype.getOrAdd = function (key, val) {
  64190. var curVal = this.get(key);
  64191. if (curVal !== undefined) {
  64192. return curVal;
  64193. }
  64194. this.add(key, val);
  64195. return val;
  64196. };
  64197. /**
  64198. * Check if there's a given key in the dictionary
  64199. * @param key the key to check for
  64200. * @return true if the key is present, false otherwise
  64201. */
  64202. StringDictionary.prototype.contains = function (key) {
  64203. return this._data[key] !== undefined;
  64204. };
  64205. /**
  64206. * Add a new key and its corresponding value
  64207. * @param key the key to add
  64208. * @param value the value corresponding to the key
  64209. * @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
  64210. */
  64211. StringDictionary.prototype.add = function (key, value) {
  64212. if (this._data[key] !== undefined) {
  64213. return false;
  64214. }
  64215. this._data[key] = value;
  64216. ++this._count;
  64217. return true;
  64218. };
  64219. StringDictionary.prototype.set = function (key, value) {
  64220. if (this._data[key] === undefined) {
  64221. return false;
  64222. }
  64223. this._data[key] = value;
  64224. return true;
  64225. };
  64226. /**
  64227. * Get the element of the given key and remove it from the dictionary
  64228. * @param key
  64229. */
  64230. StringDictionary.prototype.getAndRemove = function (key) {
  64231. var val = this.get(key);
  64232. if (val !== undefined) {
  64233. delete this._data[key];
  64234. --this._count;
  64235. return val;
  64236. }
  64237. return null;
  64238. };
  64239. /**
  64240. * Remove a key/value from the dictionary.
  64241. * @param key the key to remove
  64242. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64243. */
  64244. StringDictionary.prototype.remove = function (key) {
  64245. if (this.contains(key)) {
  64246. delete this._data[key];
  64247. --this._count;
  64248. return true;
  64249. }
  64250. return false;
  64251. };
  64252. /**
  64253. * Clear the whole content of the dictionary
  64254. */
  64255. StringDictionary.prototype.clear = function () {
  64256. this._data = {};
  64257. this._count = 0;
  64258. };
  64259. Object.defineProperty(StringDictionary.prototype, "count", {
  64260. get: function () {
  64261. return this._count;
  64262. },
  64263. enumerable: true,
  64264. configurable: true
  64265. });
  64266. /**
  64267. * Execute a callback on each key/val of the dictionary.
  64268. * Note that you can remove any element in this dictionary in the callback implementation
  64269. * @param callback the callback to execute on a given key/value pair
  64270. */
  64271. StringDictionary.prototype.forEach = function (callback) {
  64272. for (var cur in this._data) {
  64273. var val = this._data[cur];
  64274. callback(cur, val);
  64275. }
  64276. };
  64277. /**
  64278. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64279. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64280. * Note that you can remove any element in this dictionary in the callback implementation
  64281. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64282. */
  64283. StringDictionary.prototype.first = function (callback) {
  64284. for (var cur in this._data) {
  64285. var val = this._data[cur];
  64286. var res = callback(cur, val);
  64287. if (res) {
  64288. return res;
  64289. }
  64290. }
  64291. return null;
  64292. };
  64293. return StringDictionary;
  64294. }());
  64295. BABYLON.StringDictionary = StringDictionary;
  64296. })(BABYLON || (BABYLON = {}));
  64297. //# sourceMappingURL=babylon.stringDictionary.js.map
  64298. "use strict";
  64299. var BABYLON;
  64300. (function (BABYLON) {
  64301. var Tags = /** @class */ (function () {
  64302. function Tags() {
  64303. }
  64304. Tags.EnableFor = function (obj) {
  64305. obj._tags = obj._tags || {};
  64306. obj.hasTags = function () {
  64307. return Tags.HasTags(obj);
  64308. };
  64309. obj.addTags = function (tagsString) {
  64310. return Tags.AddTagsTo(obj, tagsString);
  64311. };
  64312. obj.removeTags = function (tagsString) {
  64313. return Tags.RemoveTagsFrom(obj, tagsString);
  64314. };
  64315. obj.matchesTagsQuery = function (tagsQuery) {
  64316. return Tags.MatchesQuery(obj, tagsQuery);
  64317. };
  64318. };
  64319. Tags.DisableFor = function (obj) {
  64320. delete obj._tags;
  64321. delete obj.hasTags;
  64322. delete obj.addTags;
  64323. delete obj.removeTags;
  64324. delete obj.matchesTagsQuery;
  64325. };
  64326. Tags.HasTags = function (obj) {
  64327. if (!obj._tags) {
  64328. return false;
  64329. }
  64330. return !BABYLON.Tools.IsEmpty(obj._tags);
  64331. };
  64332. Tags.GetTags = function (obj, asString) {
  64333. if (asString === void 0) { asString = true; }
  64334. if (!obj._tags) {
  64335. return null;
  64336. }
  64337. if (asString) {
  64338. var tagsArray = [];
  64339. for (var tag in obj._tags) {
  64340. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64341. tagsArray.push(tag);
  64342. }
  64343. }
  64344. return tagsArray.join(" ");
  64345. }
  64346. else {
  64347. return obj._tags;
  64348. }
  64349. };
  64350. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64351. // a tag cannot start with '||', '&&', and '!'
  64352. // it cannot contain whitespaces
  64353. Tags.AddTagsTo = function (obj, tagsString) {
  64354. if (!tagsString) {
  64355. return;
  64356. }
  64357. if (typeof tagsString !== "string") {
  64358. return;
  64359. }
  64360. var tags = tagsString.split(" ");
  64361. tags.forEach(function (tag, index, array) {
  64362. Tags._AddTagTo(obj, tag);
  64363. });
  64364. };
  64365. Tags._AddTagTo = function (obj, tag) {
  64366. tag = tag.trim();
  64367. if (tag === "" || tag === "true" || tag === "false") {
  64368. return;
  64369. }
  64370. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64371. return;
  64372. }
  64373. Tags.EnableFor(obj);
  64374. obj._tags[tag] = true;
  64375. };
  64376. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64377. if (!Tags.HasTags(obj)) {
  64378. return;
  64379. }
  64380. var tags = tagsString.split(" ");
  64381. for (var t in tags) {
  64382. Tags._RemoveTagFrom(obj, tags[t]);
  64383. }
  64384. };
  64385. Tags._RemoveTagFrom = function (obj, tag) {
  64386. delete obj._tags[tag];
  64387. };
  64388. Tags.MatchesQuery = function (obj, tagsQuery) {
  64389. if (tagsQuery === undefined) {
  64390. return true;
  64391. }
  64392. if (tagsQuery === "") {
  64393. return Tags.HasTags(obj);
  64394. }
  64395. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64396. };
  64397. return Tags;
  64398. }());
  64399. BABYLON.Tags = Tags;
  64400. })(BABYLON || (BABYLON = {}));
  64401. //# sourceMappingURL=babylon.tags.js.map
  64402. "use strict";
  64403. var BABYLON;
  64404. (function (BABYLON) {
  64405. var AndOrNotEvaluator = /** @class */ (function () {
  64406. function AndOrNotEvaluator() {
  64407. }
  64408. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64409. if (!query.match(/\([^\(\)]*\)/g)) {
  64410. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64411. }
  64412. else {
  64413. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64414. // remove parenthesis
  64415. r = r.slice(1, r.length - 1);
  64416. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64417. });
  64418. }
  64419. if (query === "true") {
  64420. return true;
  64421. }
  64422. if (query === "false") {
  64423. return false;
  64424. }
  64425. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64426. };
  64427. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64428. evaluateCallback = evaluateCallback || (function (r) {
  64429. return r === "true" ? true : false;
  64430. });
  64431. var result;
  64432. var or = parenthesisContent.split("||");
  64433. for (var i in or) {
  64434. if (or.hasOwnProperty(i)) {
  64435. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64436. var and = ori.split("&&");
  64437. if (and.length > 1) {
  64438. for (var j = 0; j < and.length; ++j) {
  64439. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64440. if (andj !== "true" && andj !== "false") {
  64441. if (andj[0] === "!") {
  64442. result = !evaluateCallback(andj.substring(1));
  64443. }
  64444. else {
  64445. result = evaluateCallback(andj);
  64446. }
  64447. }
  64448. else {
  64449. result = andj === "true" ? true : false;
  64450. }
  64451. if (!result) {
  64452. ori = "false";
  64453. break;
  64454. }
  64455. }
  64456. }
  64457. if (result || ori === "true") {
  64458. result = true;
  64459. break;
  64460. }
  64461. // result equals false (or undefined)
  64462. if (ori !== "true" && ori !== "false") {
  64463. if (ori[0] === "!") {
  64464. result = !evaluateCallback(ori.substring(1));
  64465. }
  64466. else {
  64467. result = evaluateCallback(ori);
  64468. }
  64469. }
  64470. else {
  64471. result = ori === "true" ? true : false;
  64472. }
  64473. }
  64474. }
  64475. // the whole parenthesis scope is replaced by 'true' or 'false'
  64476. return result ? "true" : "false";
  64477. };
  64478. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64479. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64480. // remove whitespaces
  64481. r = r.replace(/[\s]/g, function () { return ""; });
  64482. return r.length % 2 ? "!" : "";
  64483. });
  64484. booleanString = booleanString.trim();
  64485. if (booleanString === "!true") {
  64486. booleanString = "false";
  64487. }
  64488. else if (booleanString === "!false") {
  64489. booleanString = "true";
  64490. }
  64491. return booleanString;
  64492. };
  64493. return AndOrNotEvaluator;
  64494. }());
  64495. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64496. })(BABYLON || (BABYLON = {}));
  64497. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64498. "use strict";
  64499. var BABYLON;
  64500. (function (BABYLON) {
  64501. var Database = /** @class */ (function () {
  64502. function Database(urlToScene, callbackManifestChecked) {
  64503. // Handling various flavors of prefixed version of IndexedDB
  64504. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64505. this.callbackManifestChecked = callbackManifestChecked;
  64506. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64507. this.db = null;
  64508. this._enableSceneOffline = false;
  64509. this._enableTexturesOffline = false;
  64510. this.manifestVersionFound = 0;
  64511. this.mustUpdateRessources = false;
  64512. this.hasReachedQuota = false;
  64513. if (!Database.IDBStorageEnabled) {
  64514. this.callbackManifestChecked(true);
  64515. }
  64516. else {
  64517. this.checkManifestFile();
  64518. }
  64519. }
  64520. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64521. get: function () {
  64522. return this._enableSceneOffline;
  64523. },
  64524. enumerable: true,
  64525. configurable: true
  64526. });
  64527. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64528. get: function () {
  64529. return this._enableTexturesOffline;
  64530. },
  64531. enumerable: true,
  64532. configurable: true
  64533. });
  64534. Database.prototype.checkManifestFile = function () {
  64535. var _this = this;
  64536. var noManifestFile = function () {
  64537. _this._enableSceneOffline = false;
  64538. _this._enableTexturesOffline = false;
  64539. _this.callbackManifestChecked(false);
  64540. };
  64541. var timeStampUsed = false;
  64542. var manifestURL = this.currentSceneUrl + ".manifest";
  64543. var xhr = new XMLHttpRequest();
  64544. if (navigator.onLine) {
  64545. // Adding a timestamp to by-pass browsers' cache
  64546. timeStampUsed = true;
  64547. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64548. }
  64549. xhr.open("GET", manifestURL, true);
  64550. xhr.addEventListener("load", function () {
  64551. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64552. try {
  64553. var manifestFile = JSON.parse(xhr.response);
  64554. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64555. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64556. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64557. _this.manifestVersionFound = manifestFile.version;
  64558. }
  64559. if (_this.callbackManifestChecked) {
  64560. _this.callbackManifestChecked(true);
  64561. }
  64562. }
  64563. catch (ex) {
  64564. noManifestFile();
  64565. }
  64566. }
  64567. else {
  64568. noManifestFile();
  64569. }
  64570. }, false);
  64571. xhr.addEventListener("error", function (event) {
  64572. if (timeStampUsed) {
  64573. timeStampUsed = false;
  64574. // Let's retry without the timeStamp
  64575. // It could fail when coupled with HTML5 Offline API
  64576. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64577. xhr.open("GET", retryManifestURL, true);
  64578. xhr.send();
  64579. }
  64580. else {
  64581. noManifestFile();
  64582. }
  64583. }, false);
  64584. try {
  64585. xhr.send();
  64586. }
  64587. catch (ex) {
  64588. BABYLON.Tools.Error("Error on XHR send request.");
  64589. this.callbackManifestChecked(false);
  64590. }
  64591. };
  64592. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64593. var _this = this;
  64594. var handleError = function () {
  64595. _this.isSupported = false;
  64596. if (errorCallback)
  64597. errorCallback();
  64598. };
  64599. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64600. // Your browser doesn't support IndexedDB
  64601. this.isSupported = false;
  64602. if (errorCallback)
  64603. errorCallback();
  64604. }
  64605. else {
  64606. // If the DB hasn't been opened or created yet
  64607. if (!this.db) {
  64608. this.hasReachedQuota = false;
  64609. this.isSupported = true;
  64610. var request = this.idbFactory.open("babylonjs", 1);
  64611. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64612. request.onerror = function (event) {
  64613. handleError();
  64614. };
  64615. // executes when a version change transaction cannot complete due to other active transactions
  64616. request.onblocked = function (event) {
  64617. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64618. handleError();
  64619. };
  64620. // DB has been opened successfully
  64621. request.onsuccess = function (event) {
  64622. _this.db = request.result;
  64623. successCallback();
  64624. };
  64625. // Initialization of the DB. Creating Scenes & Textures stores
  64626. request.onupgradeneeded = function (event) {
  64627. _this.db = (event.target).result;
  64628. if (_this.db) {
  64629. try {
  64630. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64631. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64632. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64633. }
  64634. catch (ex) {
  64635. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64636. handleError();
  64637. }
  64638. }
  64639. };
  64640. }
  64641. else {
  64642. if (successCallback)
  64643. successCallback();
  64644. }
  64645. }
  64646. };
  64647. Database.prototype.loadImageFromDB = function (url, image) {
  64648. var _this = this;
  64649. var completeURL = Database.ReturnFullUrlLocation(url);
  64650. var saveAndLoadImage = function () {
  64651. if (!_this.hasReachedQuota && _this.db !== null) {
  64652. // the texture is not yet in the DB, let's try to save it
  64653. _this._saveImageIntoDBAsync(completeURL, image);
  64654. }
  64655. else {
  64656. image.src = url;
  64657. }
  64658. };
  64659. if (!this.mustUpdateRessources) {
  64660. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64661. }
  64662. else {
  64663. saveAndLoadImage();
  64664. }
  64665. };
  64666. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64667. if (this.isSupported && this.db !== null) {
  64668. var texture;
  64669. var transaction = this.db.transaction(["textures"]);
  64670. transaction.onabort = function (event) {
  64671. image.src = url;
  64672. };
  64673. transaction.oncomplete = function (event) {
  64674. var blobTextureURL;
  64675. if (texture) {
  64676. var URL = window.URL || window.webkitURL;
  64677. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64678. image.onerror = function () {
  64679. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64680. image.src = url;
  64681. };
  64682. image.src = blobTextureURL;
  64683. }
  64684. else {
  64685. notInDBCallback();
  64686. }
  64687. };
  64688. var getRequest = transaction.objectStore("textures").get(url);
  64689. getRequest.onsuccess = function (event) {
  64690. texture = (event.target).result;
  64691. };
  64692. getRequest.onerror = function (event) {
  64693. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64694. image.src = url;
  64695. };
  64696. }
  64697. else {
  64698. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64699. image.src = url;
  64700. }
  64701. };
  64702. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64703. var _this = this;
  64704. if (this.isSupported) {
  64705. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64706. var generateBlobUrl = function () {
  64707. var blobTextureURL;
  64708. if (blob) {
  64709. var URL = window.URL || window.webkitURL;
  64710. try {
  64711. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64712. }
  64713. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64714. catch (ex) {
  64715. blobTextureURL = URL.createObjectURL(blob);
  64716. }
  64717. }
  64718. if (blobTextureURL) {
  64719. image.src = blobTextureURL;
  64720. }
  64721. };
  64722. if (Database.IsUASupportingBlobStorage) {
  64723. var xhr = new XMLHttpRequest(), blob;
  64724. xhr.open("GET", url, true);
  64725. xhr.responseType = "blob";
  64726. xhr.addEventListener("load", function () {
  64727. if (xhr.status === 200 && _this.db) {
  64728. // Blob as response (XHR2)
  64729. blob = xhr.response;
  64730. var transaction = _this.db.transaction(["textures"], "readwrite");
  64731. // the transaction could abort because of a QuotaExceededError error
  64732. transaction.onabort = function (event) {
  64733. try {
  64734. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64735. var srcElement = (event.srcElement || event.target);
  64736. var error = srcElement.error;
  64737. if (error && error.name === "QuotaExceededError") {
  64738. _this.hasReachedQuota = true;
  64739. }
  64740. }
  64741. catch (ex) { }
  64742. generateBlobUrl();
  64743. };
  64744. transaction.oncomplete = function (event) {
  64745. generateBlobUrl();
  64746. };
  64747. var newTexture = { textureUrl: url, data: blob };
  64748. try {
  64749. // Put the blob into the dabase
  64750. var addRequest = transaction.objectStore("textures").put(newTexture);
  64751. addRequest.onsuccess = function (event) {
  64752. };
  64753. addRequest.onerror = function (event) {
  64754. generateBlobUrl();
  64755. };
  64756. }
  64757. catch (ex) {
  64758. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64759. if (ex.code === 25) {
  64760. Database.IsUASupportingBlobStorage = false;
  64761. }
  64762. image.src = url;
  64763. }
  64764. }
  64765. else {
  64766. image.src = url;
  64767. }
  64768. }, false);
  64769. xhr.addEventListener("error", function (event) {
  64770. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64771. image.src = url;
  64772. }, false);
  64773. xhr.send();
  64774. }
  64775. else {
  64776. image.src = url;
  64777. }
  64778. }
  64779. else {
  64780. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64781. image.src = url;
  64782. }
  64783. };
  64784. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64785. var _this = this;
  64786. var updateVersion = function () {
  64787. // the version is not yet in the DB or we need to update it
  64788. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64789. };
  64790. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64791. };
  64792. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64793. var _this = this;
  64794. if (this.isSupported && this.db) {
  64795. var version;
  64796. try {
  64797. var transaction = this.db.transaction(["versions"]);
  64798. transaction.oncomplete = function (event) {
  64799. if (version) {
  64800. // If the version in the JSON file is > than the version in DB
  64801. if (_this.manifestVersionFound > version.data) {
  64802. _this.mustUpdateRessources = true;
  64803. updateInDBCallback();
  64804. }
  64805. else {
  64806. callback(version.data);
  64807. }
  64808. }
  64809. else {
  64810. _this.mustUpdateRessources = true;
  64811. updateInDBCallback();
  64812. }
  64813. };
  64814. transaction.onabort = function (event) {
  64815. callback(-1);
  64816. };
  64817. var getRequest = transaction.objectStore("versions").get(url);
  64818. getRequest.onsuccess = function (event) {
  64819. version = (event.target).result;
  64820. };
  64821. getRequest.onerror = function (event) {
  64822. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64823. callback(-1);
  64824. };
  64825. }
  64826. catch (ex) {
  64827. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64828. callback(-1);
  64829. }
  64830. }
  64831. else {
  64832. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64833. callback(-1);
  64834. }
  64835. };
  64836. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64837. var _this = this;
  64838. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64839. try {
  64840. // Open a transaction to the database
  64841. var transaction = this.db.transaction(["versions"], "readwrite");
  64842. // the transaction could abort because of a QuotaExceededError error
  64843. transaction.onabort = function (event) {
  64844. try {
  64845. var error = event.srcElement['error'];
  64846. if (error && error.name === "QuotaExceededError") {
  64847. _this.hasReachedQuota = true;
  64848. }
  64849. }
  64850. catch (ex) { }
  64851. callback(-1);
  64852. };
  64853. transaction.oncomplete = function (event) {
  64854. callback(_this.manifestVersionFound);
  64855. };
  64856. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64857. // Put the scene into the database
  64858. var addRequest = transaction.objectStore("versions").put(newVersion);
  64859. addRequest.onsuccess = function (event) {
  64860. };
  64861. addRequest.onerror = function (event) {
  64862. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64863. };
  64864. }
  64865. catch (ex) {
  64866. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64867. callback(-1);
  64868. }
  64869. }
  64870. else {
  64871. callback(-1);
  64872. }
  64873. };
  64874. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64875. var _this = this;
  64876. var completeUrl = Database.ReturnFullUrlLocation(url);
  64877. var saveAndLoadFile = function () {
  64878. // the scene is not yet in the DB, let's try to save it
  64879. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64880. };
  64881. this._checkVersionFromDB(completeUrl, function (version) {
  64882. if (version !== -1) {
  64883. if (!_this.mustUpdateRessources) {
  64884. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64885. }
  64886. else {
  64887. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64888. }
  64889. }
  64890. else {
  64891. if (errorCallback) {
  64892. errorCallback();
  64893. }
  64894. }
  64895. });
  64896. };
  64897. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64898. if (this.isSupported && this.db) {
  64899. var targetStore;
  64900. if (url.indexOf(".babylon") !== -1) {
  64901. targetStore = "scenes";
  64902. }
  64903. else {
  64904. targetStore = "textures";
  64905. }
  64906. var file;
  64907. var transaction = this.db.transaction([targetStore]);
  64908. transaction.oncomplete = function (event) {
  64909. if (file) {
  64910. callback(file.data);
  64911. }
  64912. else {
  64913. notInDBCallback();
  64914. }
  64915. };
  64916. transaction.onabort = function (event) {
  64917. notInDBCallback();
  64918. };
  64919. var getRequest = transaction.objectStore(targetStore).get(url);
  64920. getRequest.onsuccess = function (event) {
  64921. file = (event.target).result;
  64922. };
  64923. getRequest.onerror = function (event) {
  64924. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64925. notInDBCallback();
  64926. };
  64927. }
  64928. else {
  64929. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64930. callback();
  64931. }
  64932. };
  64933. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64934. var _this = this;
  64935. if (this.isSupported) {
  64936. var targetStore;
  64937. if (url.indexOf(".babylon") !== -1) {
  64938. targetStore = "scenes";
  64939. }
  64940. else {
  64941. targetStore = "textures";
  64942. }
  64943. // Create XHR
  64944. var xhr = new XMLHttpRequest();
  64945. var fileData;
  64946. xhr.open("GET", url, true);
  64947. if (useArrayBuffer) {
  64948. xhr.responseType = "arraybuffer";
  64949. }
  64950. if (progressCallback) {
  64951. xhr.onprogress = progressCallback;
  64952. }
  64953. xhr.addEventListener("load", function () {
  64954. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64955. // Blob as response (XHR2)
  64956. //fileData = xhr.responseText;
  64957. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64958. if (!_this.hasReachedQuota && _this.db) {
  64959. // Open a transaction to the database
  64960. var transaction = _this.db.transaction([targetStore], "readwrite");
  64961. // the transaction could abort because of a QuotaExceededError error
  64962. transaction.onabort = function (event) {
  64963. try {
  64964. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64965. var error = event.srcElement['error'];
  64966. if (error && error.name === "QuotaExceededError") {
  64967. _this.hasReachedQuota = true;
  64968. }
  64969. }
  64970. catch (ex) { }
  64971. callback(fileData);
  64972. };
  64973. transaction.oncomplete = function (event) {
  64974. callback(fileData);
  64975. };
  64976. var newFile;
  64977. if (targetStore === "scenes") {
  64978. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64979. }
  64980. else {
  64981. newFile = { textureUrl: url, data: fileData };
  64982. }
  64983. try {
  64984. // Put the scene into the database
  64985. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64986. addRequest.onsuccess = function (event) {
  64987. };
  64988. addRequest.onerror = function (event) {
  64989. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64990. };
  64991. }
  64992. catch (ex) {
  64993. callback(fileData);
  64994. }
  64995. }
  64996. else {
  64997. callback(fileData);
  64998. }
  64999. }
  65000. else {
  65001. callback();
  65002. }
  65003. }, false);
  65004. xhr.addEventListener("error", function (event) {
  65005. BABYLON.Tools.Error("error on XHR request.");
  65006. callback();
  65007. }, false);
  65008. xhr.send();
  65009. }
  65010. else {
  65011. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65012. callback();
  65013. }
  65014. };
  65015. Database.IsUASupportingBlobStorage = true;
  65016. Database.IDBStorageEnabled = true;
  65017. Database.parseURL = function (url) {
  65018. var a = document.createElement('a');
  65019. a.href = url;
  65020. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  65021. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  65022. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  65023. return absLocation;
  65024. };
  65025. Database.ReturnFullUrlLocation = function (url) {
  65026. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  65027. return (Database.parseURL(window.location.href) + url);
  65028. }
  65029. else {
  65030. return url;
  65031. }
  65032. };
  65033. return Database;
  65034. }());
  65035. BABYLON.Database = Database;
  65036. })(BABYLON || (BABYLON = {}));
  65037. //# sourceMappingURL=babylon.database.js.map
  65038. "use strict";
  65039. var BABYLON;
  65040. (function (BABYLON) {
  65041. var FresnelParameters = /** @class */ (function () {
  65042. function FresnelParameters() {
  65043. this._isEnabled = true;
  65044. this.leftColor = BABYLON.Color3.White();
  65045. this.rightColor = BABYLON.Color3.Black();
  65046. this.bias = 0;
  65047. this.power = 1;
  65048. }
  65049. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  65050. get: function () {
  65051. return this._isEnabled;
  65052. },
  65053. set: function (value) {
  65054. if (this._isEnabled === value) {
  65055. return;
  65056. }
  65057. this._isEnabled = value;
  65058. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65059. },
  65060. enumerable: true,
  65061. configurable: true
  65062. });
  65063. FresnelParameters.prototype.clone = function () {
  65064. var newFresnelParameters = new FresnelParameters();
  65065. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65066. return newFresnelParameters;
  65067. };
  65068. FresnelParameters.prototype.serialize = function () {
  65069. var serializationObject = {};
  65070. serializationObject.isEnabled = this.isEnabled;
  65071. serializationObject.leftColor = this.leftColor.asArray();
  65072. serializationObject.rightColor = this.rightColor.asArray();
  65073. serializationObject.bias = this.bias;
  65074. serializationObject.power = this.power;
  65075. return serializationObject;
  65076. };
  65077. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65078. var fresnelParameters = new FresnelParameters();
  65079. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65080. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65081. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65082. fresnelParameters.bias = parsedFresnelParameters.bias;
  65083. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65084. return fresnelParameters;
  65085. };
  65086. return FresnelParameters;
  65087. }());
  65088. BABYLON.FresnelParameters = FresnelParameters;
  65089. })(BABYLON || (BABYLON = {}));
  65090. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65091. "use strict";
  65092. var BABYLON;
  65093. (function (BABYLON) {
  65094. var MultiMaterial = /** @class */ (function (_super) {
  65095. __extends(MultiMaterial, _super);
  65096. function MultiMaterial(name, scene) {
  65097. var _this = _super.call(this, name, scene, true) || this;
  65098. scene.multiMaterials.push(_this);
  65099. _this.subMaterials = new Array();
  65100. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65101. return _this;
  65102. }
  65103. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65104. get: function () {
  65105. return this._subMaterials;
  65106. },
  65107. set: function (value) {
  65108. this._subMaterials = value;
  65109. this._hookArray(value);
  65110. },
  65111. enumerable: true,
  65112. configurable: true
  65113. });
  65114. MultiMaterial.prototype._hookArray = function (array) {
  65115. var _this = this;
  65116. var oldPush = array.push;
  65117. array.push = function () {
  65118. var items = [];
  65119. for (var _i = 0; _i < arguments.length; _i++) {
  65120. items[_i] = arguments[_i];
  65121. }
  65122. var result = oldPush.apply(array, items);
  65123. _this._markAllSubMeshesAsTexturesDirty();
  65124. return result;
  65125. };
  65126. var oldSplice = array.splice;
  65127. array.splice = function (index, deleteCount) {
  65128. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65129. _this._markAllSubMeshesAsTexturesDirty();
  65130. return deleted;
  65131. };
  65132. };
  65133. // Properties
  65134. MultiMaterial.prototype.getSubMaterial = function (index) {
  65135. if (index < 0 || index >= this.subMaterials.length) {
  65136. return this.getScene().defaultMaterial;
  65137. }
  65138. return this.subMaterials[index];
  65139. };
  65140. MultiMaterial.prototype.getActiveTextures = function () {
  65141. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65142. if (subMaterial) {
  65143. return subMaterial.getActiveTextures();
  65144. }
  65145. else {
  65146. return [];
  65147. }
  65148. }));
  65149. var _a;
  65150. };
  65151. // Methods
  65152. MultiMaterial.prototype.getClassName = function () {
  65153. return "MultiMaterial";
  65154. };
  65155. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65156. for (var index = 0; index < this.subMaterials.length; index++) {
  65157. var subMaterial = this.subMaterials[index];
  65158. if (subMaterial) {
  65159. if (subMaterial.storeEffectOnSubMeshes) {
  65160. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65161. return false;
  65162. }
  65163. continue;
  65164. }
  65165. if (!subMaterial.isReady(mesh)) {
  65166. return false;
  65167. }
  65168. }
  65169. }
  65170. return true;
  65171. };
  65172. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65173. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65174. for (var index = 0; index < this.subMaterials.length; index++) {
  65175. var subMaterial = null;
  65176. var current = this.subMaterials[index];
  65177. if (cloneChildren && current) {
  65178. subMaterial = current.clone(name + "-" + current.name);
  65179. }
  65180. else {
  65181. subMaterial = this.subMaterials[index];
  65182. }
  65183. newMultiMaterial.subMaterials.push(subMaterial);
  65184. }
  65185. return newMultiMaterial;
  65186. };
  65187. MultiMaterial.prototype.serialize = function () {
  65188. var serializationObject = {};
  65189. serializationObject.name = this.name;
  65190. serializationObject.id = this.id;
  65191. if (BABYLON.Tags) {
  65192. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65193. }
  65194. serializationObject.materials = [];
  65195. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65196. var subMat = this.subMaterials[matIndex];
  65197. if (subMat) {
  65198. serializationObject.materials.push(subMat.id);
  65199. }
  65200. else {
  65201. serializationObject.materials.push(null);
  65202. }
  65203. }
  65204. return serializationObject;
  65205. };
  65206. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65207. var scene = this.getScene();
  65208. if (!scene) {
  65209. return;
  65210. }
  65211. var index = scene.multiMaterials.indexOf(this);
  65212. if (index >= 0) {
  65213. scene.multiMaterials.splice(index, 1);
  65214. }
  65215. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65216. };
  65217. return MultiMaterial;
  65218. }(BABYLON.Material));
  65219. BABYLON.MultiMaterial = MultiMaterial;
  65220. })(BABYLON || (BABYLON = {}));
  65221. //# sourceMappingURL=babylon.multiMaterial.js.map
  65222. "use strict";
  65223. var BABYLON;
  65224. (function (BABYLON) {
  65225. var FreeCameraTouchInput = /** @class */ (function () {
  65226. function FreeCameraTouchInput() {
  65227. this._offsetX = null;
  65228. this._offsetY = null;
  65229. this._pointerPressed = new Array();
  65230. this.touchAngularSensibility = 200000.0;
  65231. this.touchMoveSensibility = 250.0;
  65232. }
  65233. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65234. var _this = this;
  65235. var previousPosition = null;
  65236. if (this._pointerInput === undefined) {
  65237. this._onLostFocus = function (evt) {
  65238. _this._offsetX = null;
  65239. _this._offsetY = null;
  65240. };
  65241. this._pointerInput = function (p, s) {
  65242. var evt = p.event;
  65243. if (evt.pointerType === "mouse") {
  65244. return;
  65245. }
  65246. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65247. if (!noPreventDefault) {
  65248. evt.preventDefault();
  65249. }
  65250. _this._pointerPressed.push(evt.pointerId);
  65251. if (_this._pointerPressed.length !== 1) {
  65252. return;
  65253. }
  65254. previousPosition = {
  65255. x: evt.clientX,
  65256. y: evt.clientY
  65257. };
  65258. }
  65259. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65260. if (!noPreventDefault) {
  65261. evt.preventDefault();
  65262. }
  65263. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65264. if (index === -1) {
  65265. return;
  65266. }
  65267. _this._pointerPressed.splice(index, 1);
  65268. if (index != 0) {
  65269. return;
  65270. }
  65271. previousPosition = null;
  65272. _this._offsetX = null;
  65273. _this._offsetY = null;
  65274. }
  65275. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65276. if (!noPreventDefault) {
  65277. evt.preventDefault();
  65278. }
  65279. if (!previousPosition) {
  65280. return;
  65281. }
  65282. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65283. if (index != 0) {
  65284. return;
  65285. }
  65286. _this._offsetX = evt.clientX - previousPosition.x;
  65287. _this._offsetY = -(evt.clientY - previousPosition.y);
  65288. }
  65289. };
  65290. }
  65291. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65292. if (this._onLostFocus) {
  65293. element.addEventListener("blur", this._onLostFocus);
  65294. }
  65295. };
  65296. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65297. if (this._pointerInput && element) {
  65298. if (this._observer) {
  65299. this.camera.getScene().onPointerObservable.remove(this._observer);
  65300. this._observer = null;
  65301. }
  65302. if (this._onLostFocus) {
  65303. element.removeEventListener("blur", this._onLostFocus);
  65304. this._onLostFocus = null;
  65305. }
  65306. this._pointerPressed = [];
  65307. this._offsetX = null;
  65308. this._offsetY = null;
  65309. }
  65310. };
  65311. FreeCameraTouchInput.prototype.checkInputs = function () {
  65312. if (this._offsetX && this._offsetY) {
  65313. var camera = this.camera;
  65314. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65315. if (this._pointerPressed.length > 1) {
  65316. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65317. }
  65318. else {
  65319. var speed = camera._computeLocalCameraSpeed();
  65320. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65321. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65322. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65323. }
  65324. }
  65325. };
  65326. FreeCameraTouchInput.prototype.getClassName = function () {
  65327. return "FreeCameraTouchInput";
  65328. };
  65329. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65330. return "touch";
  65331. };
  65332. __decorate([
  65333. BABYLON.serialize()
  65334. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65335. __decorate([
  65336. BABYLON.serialize()
  65337. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65338. return FreeCameraTouchInput;
  65339. }());
  65340. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65341. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65342. })(BABYLON || (BABYLON = {}));
  65343. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65344. "use strict";
  65345. var BABYLON;
  65346. (function (BABYLON) {
  65347. // We're mainly based on the logic defined into the FreeCamera code
  65348. var TouchCamera = /** @class */ (function (_super) {
  65349. __extends(TouchCamera, _super);
  65350. //-- end properties for backward compatibility for inputs
  65351. function TouchCamera(name, position, scene) {
  65352. var _this = _super.call(this, name, position, scene) || this;
  65353. _this.inputs.addTouch();
  65354. _this._setupInputs();
  65355. return _this;
  65356. }
  65357. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65358. //-- Begin properties for backward compatibility for inputs
  65359. get: function () {
  65360. var touch = this.inputs.attached["touch"];
  65361. if (touch)
  65362. return touch.touchAngularSensibility;
  65363. return 0;
  65364. },
  65365. set: function (value) {
  65366. var touch = this.inputs.attached["touch"];
  65367. if (touch)
  65368. touch.touchAngularSensibility = value;
  65369. },
  65370. enumerable: true,
  65371. configurable: true
  65372. });
  65373. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65374. get: function () {
  65375. var touch = this.inputs.attached["touch"];
  65376. if (touch)
  65377. return touch.touchMoveSensibility;
  65378. return 0;
  65379. },
  65380. set: function (value) {
  65381. var touch = this.inputs.attached["touch"];
  65382. if (touch)
  65383. touch.touchMoveSensibility = value;
  65384. },
  65385. enumerable: true,
  65386. configurable: true
  65387. });
  65388. TouchCamera.prototype.getClassName = function () {
  65389. return "TouchCamera";
  65390. };
  65391. TouchCamera.prototype._setupInputs = function () {
  65392. var mouse = this.inputs.attached["mouse"];
  65393. if (mouse) {
  65394. mouse.touchEnabled = false;
  65395. }
  65396. };
  65397. return TouchCamera;
  65398. }(BABYLON.FreeCamera));
  65399. BABYLON.TouchCamera = TouchCamera;
  65400. })(BABYLON || (BABYLON = {}));
  65401. //# sourceMappingURL=babylon.touchCamera.js.map
  65402. "use strict";
  65403. var BABYLON;
  65404. (function (BABYLON) {
  65405. var ProceduralTexture = /** @class */ (function (_super) {
  65406. __extends(ProceduralTexture, _super);
  65407. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65408. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65409. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65410. if (isCube === void 0) { isCube = false; }
  65411. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65412. _this.isCube = isCube;
  65413. _this.isEnabled = true;
  65414. _this._currentRefreshId = -1;
  65415. _this._refreshRate = 1;
  65416. _this._vertexBuffers = {};
  65417. _this._uniforms = new Array();
  65418. _this._samplers = new Array();
  65419. _this._textures = {};
  65420. _this._floats = {};
  65421. _this._floatsArrays = {};
  65422. _this._colors3 = {};
  65423. _this._colors4 = {};
  65424. _this._vectors2 = {};
  65425. _this._vectors3 = {};
  65426. _this._matrices = {};
  65427. _this._fallbackTextureUsed = false;
  65428. scene._proceduralTextures.push(_this);
  65429. _this._engine = scene.getEngine();
  65430. _this.name = name;
  65431. _this.isRenderTarget = true;
  65432. _this._size = size;
  65433. _this._generateMipMaps = generateMipMaps;
  65434. _this.setFragment(fragment);
  65435. _this._fallbackTexture = fallbackTexture;
  65436. if (isCube) {
  65437. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65438. _this.setFloat("face", 0);
  65439. }
  65440. else {
  65441. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65442. }
  65443. // VBO
  65444. var vertices = [];
  65445. vertices.push(1, 1);
  65446. vertices.push(-1, 1);
  65447. vertices.push(-1, -1);
  65448. vertices.push(1, -1);
  65449. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65450. _this._createIndexBuffer();
  65451. return _this;
  65452. }
  65453. ProceduralTexture.prototype._createIndexBuffer = function () {
  65454. var engine = this._engine;
  65455. // Indices
  65456. var indices = [];
  65457. indices.push(0);
  65458. indices.push(1);
  65459. indices.push(2);
  65460. indices.push(0);
  65461. indices.push(2);
  65462. indices.push(3);
  65463. this._indexBuffer = engine.createIndexBuffer(indices);
  65464. };
  65465. ProceduralTexture.prototype._rebuild = function () {
  65466. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65467. if (vb) {
  65468. vb._rebuild();
  65469. }
  65470. this._createIndexBuffer();
  65471. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65472. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65473. }
  65474. };
  65475. ProceduralTexture.prototype.reset = function () {
  65476. if (this._effect === undefined) {
  65477. return;
  65478. }
  65479. var engine = this._engine;
  65480. engine._releaseEffect(this._effect);
  65481. };
  65482. ProceduralTexture.prototype.isReady = function () {
  65483. var _this = this;
  65484. var engine = this._engine;
  65485. var shaders;
  65486. if (!this._fragment) {
  65487. return false;
  65488. }
  65489. if (this._fallbackTextureUsed) {
  65490. return true;
  65491. }
  65492. if (this._fragment.fragmentElement !== undefined) {
  65493. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65494. }
  65495. else {
  65496. shaders = { vertex: "procedural", fragment: this._fragment };
  65497. }
  65498. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65499. _this.releaseInternalTexture();
  65500. if (_this._fallbackTexture) {
  65501. _this._texture = _this._fallbackTexture._texture;
  65502. if (_this._texture) {
  65503. _this._texture.incrementReferences();
  65504. }
  65505. }
  65506. _this._fallbackTextureUsed = true;
  65507. });
  65508. return this._effect.isReady();
  65509. };
  65510. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65511. this._currentRefreshId = -1;
  65512. };
  65513. ProceduralTexture.prototype.setFragment = function (fragment) {
  65514. this._fragment = fragment;
  65515. };
  65516. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65517. get: function () {
  65518. return this._refreshRate;
  65519. },
  65520. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65521. set: function (value) {
  65522. this._refreshRate = value;
  65523. this.resetRefreshCounter();
  65524. },
  65525. enumerable: true,
  65526. configurable: true
  65527. });
  65528. ProceduralTexture.prototype._shouldRender = function () {
  65529. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65530. return false;
  65531. }
  65532. if (this._fallbackTextureUsed) {
  65533. return false;
  65534. }
  65535. if (this._currentRefreshId === -1) {
  65536. this._currentRefreshId = 1;
  65537. return true;
  65538. }
  65539. if (this.refreshRate === this._currentRefreshId) {
  65540. this._currentRefreshId = 1;
  65541. return true;
  65542. }
  65543. this._currentRefreshId++;
  65544. return false;
  65545. };
  65546. ProceduralTexture.prototype.getRenderSize = function () {
  65547. return this._size;
  65548. };
  65549. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65550. if (this._fallbackTextureUsed) {
  65551. return;
  65552. }
  65553. this.releaseInternalTexture();
  65554. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65555. };
  65556. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65557. if (this._uniforms.indexOf(uniformName) === -1) {
  65558. this._uniforms.push(uniformName);
  65559. }
  65560. };
  65561. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65562. if (this._samplers.indexOf(name) === -1) {
  65563. this._samplers.push(name);
  65564. }
  65565. this._textures[name] = texture;
  65566. return this;
  65567. };
  65568. ProceduralTexture.prototype.setFloat = function (name, value) {
  65569. this._checkUniform(name);
  65570. this._floats[name] = value;
  65571. return this;
  65572. };
  65573. ProceduralTexture.prototype.setFloats = function (name, value) {
  65574. this._checkUniform(name);
  65575. this._floatsArrays[name] = value;
  65576. return this;
  65577. };
  65578. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65579. this._checkUniform(name);
  65580. this._colors3[name] = value;
  65581. return this;
  65582. };
  65583. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65584. this._checkUniform(name);
  65585. this._colors4[name] = value;
  65586. return this;
  65587. };
  65588. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65589. this._checkUniform(name);
  65590. this._vectors2[name] = value;
  65591. return this;
  65592. };
  65593. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65594. this._checkUniform(name);
  65595. this._vectors3[name] = value;
  65596. return this;
  65597. };
  65598. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65599. this._checkUniform(name);
  65600. this._matrices[name] = value;
  65601. return this;
  65602. };
  65603. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65604. var scene = this.getScene();
  65605. if (!scene) {
  65606. return;
  65607. }
  65608. var engine = this._engine;
  65609. // Render
  65610. engine.enableEffect(this._effect);
  65611. engine.setState(false);
  65612. // Texture
  65613. for (var name in this._textures) {
  65614. this._effect.setTexture(name, this._textures[name]);
  65615. }
  65616. // Float
  65617. for (name in this._floats) {
  65618. this._effect.setFloat(name, this._floats[name]);
  65619. }
  65620. // Floats
  65621. for (name in this._floatsArrays) {
  65622. this._effect.setArray(name, this._floatsArrays[name]);
  65623. }
  65624. // Color3
  65625. for (name in this._colors3) {
  65626. this._effect.setColor3(name, this._colors3[name]);
  65627. }
  65628. // Color4
  65629. for (name in this._colors4) {
  65630. var color = this._colors4[name];
  65631. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65632. }
  65633. // Vector2
  65634. for (name in this._vectors2) {
  65635. this._effect.setVector2(name, this._vectors2[name]);
  65636. }
  65637. // Vector3
  65638. for (name in this._vectors3) {
  65639. this._effect.setVector3(name, this._vectors3[name]);
  65640. }
  65641. // Matrix
  65642. for (name in this._matrices) {
  65643. this._effect.setMatrix(name, this._matrices[name]);
  65644. }
  65645. if (!this._texture) {
  65646. return;
  65647. }
  65648. if (this.isCube) {
  65649. for (var face = 0; face < 6; face++) {
  65650. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65651. // VBOs
  65652. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65653. this._effect.setFloat("face", face);
  65654. // Clear
  65655. engine.clear(scene.clearColor, true, true, true);
  65656. // Draw order
  65657. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65658. // Mipmaps
  65659. if (face === 5) {
  65660. engine.generateMipMapsForCubemap(this._texture);
  65661. }
  65662. }
  65663. }
  65664. else {
  65665. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65666. // VBOs
  65667. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65668. // Clear
  65669. engine.clear(scene.clearColor, true, true, true);
  65670. // Draw order
  65671. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65672. }
  65673. // Unbind
  65674. engine.unBindFramebuffer(this._texture, this.isCube);
  65675. if (this.onGenerated) {
  65676. this.onGenerated();
  65677. }
  65678. };
  65679. ProceduralTexture.prototype.clone = function () {
  65680. var textureSize = this.getSize();
  65681. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65682. // Base texture
  65683. newTexture.hasAlpha = this.hasAlpha;
  65684. newTexture.level = this.level;
  65685. // RenderTarget Texture
  65686. newTexture.coordinatesMode = this.coordinatesMode;
  65687. return newTexture;
  65688. };
  65689. ProceduralTexture.prototype.dispose = function () {
  65690. var scene = this.getScene();
  65691. if (!scene) {
  65692. return;
  65693. }
  65694. var index = scene._proceduralTextures.indexOf(this);
  65695. if (index >= 0) {
  65696. scene._proceduralTextures.splice(index, 1);
  65697. }
  65698. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65699. if (vertexBuffer) {
  65700. vertexBuffer.dispose();
  65701. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65702. }
  65703. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65704. this._indexBuffer = null;
  65705. }
  65706. _super.prototype.dispose.call(this);
  65707. };
  65708. return ProceduralTexture;
  65709. }(BABYLON.Texture));
  65710. BABYLON.ProceduralTexture = ProceduralTexture;
  65711. })(BABYLON || (BABYLON = {}));
  65712. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65713. "use strict";
  65714. var BABYLON;
  65715. (function (BABYLON) {
  65716. var CustomProceduralTexture = /** @class */ (function (_super) {
  65717. __extends(CustomProceduralTexture, _super);
  65718. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65719. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65720. _this._animate = true;
  65721. _this._time = 0;
  65722. _this._texturePath = texturePath;
  65723. //Try to load json
  65724. _this.loadJson(texturePath);
  65725. _this.refreshRate = 1;
  65726. return _this;
  65727. }
  65728. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65729. var _this = this;
  65730. var noConfigFile = function () {
  65731. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65732. try {
  65733. _this.setFragment(_this._texturePath);
  65734. }
  65735. catch (ex) {
  65736. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65737. }
  65738. };
  65739. var configFileUrl = jsonUrl + "/config.json";
  65740. var xhr = new XMLHttpRequest();
  65741. xhr.open("GET", configFileUrl, true);
  65742. xhr.addEventListener("load", function () {
  65743. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65744. try {
  65745. _this._config = JSON.parse(xhr.response);
  65746. _this.updateShaderUniforms();
  65747. _this.updateTextures();
  65748. _this.setFragment(_this._texturePath + "/custom");
  65749. _this._animate = _this._config.animate;
  65750. _this.refreshRate = _this._config.refreshrate;
  65751. }
  65752. catch (ex) {
  65753. noConfigFile();
  65754. }
  65755. }
  65756. else {
  65757. noConfigFile();
  65758. }
  65759. }, false);
  65760. xhr.addEventListener("error", function () {
  65761. noConfigFile();
  65762. }, false);
  65763. try {
  65764. xhr.send();
  65765. }
  65766. catch (ex) {
  65767. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65768. }
  65769. };
  65770. CustomProceduralTexture.prototype.isReady = function () {
  65771. if (!_super.prototype.isReady.call(this)) {
  65772. return false;
  65773. }
  65774. for (var name in this._textures) {
  65775. var texture = this._textures[name];
  65776. if (!texture.isReady()) {
  65777. return false;
  65778. }
  65779. }
  65780. return true;
  65781. };
  65782. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65783. var scene = this.getScene();
  65784. if (this._animate && scene) {
  65785. this._time += scene.getAnimationRatio() * 0.03;
  65786. this.updateShaderUniforms();
  65787. }
  65788. _super.prototype.render.call(this, useCameraPostProcess);
  65789. };
  65790. CustomProceduralTexture.prototype.updateTextures = function () {
  65791. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65792. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65793. }
  65794. };
  65795. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65796. if (this._config) {
  65797. for (var j = 0; j < this._config.uniforms.length; j++) {
  65798. var uniform = this._config.uniforms[j];
  65799. switch (uniform.type) {
  65800. case "float":
  65801. this.setFloat(uniform.name, uniform.value);
  65802. break;
  65803. case "color3":
  65804. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65805. break;
  65806. case "color4":
  65807. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65808. break;
  65809. case "vector2":
  65810. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65811. break;
  65812. case "vector3":
  65813. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65814. break;
  65815. }
  65816. }
  65817. }
  65818. this.setFloat("time", this._time);
  65819. };
  65820. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65821. get: function () {
  65822. return this._animate;
  65823. },
  65824. set: function (value) {
  65825. this._animate = value;
  65826. },
  65827. enumerable: true,
  65828. configurable: true
  65829. });
  65830. return CustomProceduralTexture;
  65831. }(BABYLON.ProceduralTexture));
  65832. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65833. })(BABYLON || (BABYLON = {}));
  65834. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65835. "use strict";
  65836. var BABYLON;
  65837. (function (BABYLON) {
  65838. var FreeCameraGamepadInput = /** @class */ (function () {
  65839. function FreeCameraGamepadInput() {
  65840. this.gamepadAngularSensibility = 200;
  65841. this.gamepadMoveSensibility = 40;
  65842. // private members
  65843. this._cameraTransform = BABYLON.Matrix.Identity();
  65844. this._deltaTransform = BABYLON.Vector3.Zero();
  65845. this._vector3 = BABYLON.Vector3.Zero();
  65846. this._vector2 = BABYLON.Vector2.Zero();
  65847. }
  65848. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65849. var _this = this;
  65850. var manager = this.camera.getScene().gamepadManager;
  65851. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65852. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65853. // prioritize XBOX gamepads.
  65854. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65855. _this.gamepad = gamepad;
  65856. }
  65857. }
  65858. });
  65859. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65860. if (_this.gamepad === gamepad) {
  65861. _this.gamepad = null;
  65862. }
  65863. });
  65864. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65865. };
  65866. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65867. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65868. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65869. this.gamepad = null;
  65870. };
  65871. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65872. if (this.gamepad && this.gamepad.leftStick) {
  65873. var camera = this.camera;
  65874. var LSValues = this.gamepad.leftStick;
  65875. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65876. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65877. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65878. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65879. var RSValues = this.gamepad.rightStick;
  65880. if (RSValues) {
  65881. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65882. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65883. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65884. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65885. }
  65886. else {
  65887. RSValues = { x: 0, y: 0 };
  65888. }
  65889. if (!camera.rotationQuaternion) {
  65890. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65891. }
  65892. else {
  65893. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65894. }
  65895. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65896. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65897. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65898. camera.cameraDirection.addInPlace(this._deltaTransform);
  65899. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65900. camera.cameraRotation.addInPlace(this._vector2);
  65901. }
  65902. };
  65903. FreeCameraGamepadInput.prototype.getClassName = function () {
  65904. return "FreeCameraGamepadInput";
  65905. };
  65906. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65907. return "gamepad";
  65908. };
  65909. __decorate([
  65910. BABYLON.serialize()
  65911. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65912. __decorate([
  65913. BABYLON.serialize()
  65914. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65915. return FreeCameraGamepadInput;
  65916. }());
  65917. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65918. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65919. })(BABYLON || (BABYLON = {}));
  65920. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65921. "use strict";
  65922. var BABYLON;
  65923. (function (BABYLON) {
  65924. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65925. function ArcRotateCameraGamepadInput() {
  65926. this.gamepadRotationSensibility = 80;
  65927. this.gamepadMoveSensibility = 40;
  65928. }
  65929. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65930. var _this = this;
  65931. var manager = this.camera.getScene().gamepadManager;
  65932. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65933. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65934. // prioritize XBOX gamepads.
  65935. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65936. _this.gamepad = gamepad;
  65937. }
  65938. }
  65939. });
  65940. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65941. if (_this.gamepad === gamepad) {
  65942. _this.gamepad = null;
  65943. }
  65944. });
  65945. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65946. };
  65947. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65948. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65949. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65950. this.gamepad = null;
  65951. };
  65952. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65953. if (this.gamepad) {
  65954. var camera = this.camera;
  65955. var RSValues = this.gamepad.rightStick;
  65956. if (RSValues) {
  65957. if (RSValues.x != 0) {
  65958. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65959. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65960. camera.inertialAlphaOffset += normalizedRX;
  65961. }
  65962. }
  65963. if (RSValues.y != 0) {
  65964. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65965. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65966. camera.inertialBetaOffset += normalizedRY;
  65967. }
  65968. }
  65969. }
  65970. var LSValues = this.gamepad.leftStick;
  65971. if (LSValues && LSValues.y != 0) {
  65972. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65973. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65974. this.camera.inertialRadiusOffset -= normalizedLY;
  65975. }
  65976. }
  65977. }
  65978. };
  65979. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65980. return "ArcRotateCameraGamepadInput";
  65981. };
  65982. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65983. return "gamepad";
  65984. };
  65985. __decorate([
  65986. BABYLON.serialize()
  65987. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65988. __decorate([
  65989. BABYLON.serialize()
  65990. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65991. return ArcRotateCameraGamepadInput;
  65992. }());
  65993. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65994. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65995. })(BABYLON || (BABYLON = {}));
  65996. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65997. "use strict";
  65998. var BABYLON;
  65999. (function (BABYLON) {
  66000. var GamepadManager = /** @class */ (function () {
  66001. function GamepadManager(_scene) {
  66002. var _this = this;
  66003. this._scene = _scene;
  66004. this._babylonGamepads = [];
  66005. this._oneGamepadConnected = false;
  66006. this._isMonitoring = false;
  66007. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  66008. if (!BABYLON.Tools.IsWindowObjectExist()) {
  66009. this._gamepadEventSupported = false;
  66010. }
  66011. else {
  66012. this._gamepadEventSupported = 'GamepadEvent' in window;
  66013. this._gamepadSupport = (navigator.getGamepads ||
  66014. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  66015. }
  66016. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  66017. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  66018. for (var i in _this._babylonGamepads) {
  66019. var gamepad = _this._babylonGamepads[i];
  66020. if (gamepad && gamepad._isConnected) {
  66021. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  66022. }
  66023. }
  66024. });
  66025. this._onGamepadConnectedEvent = function (evt) {
  66026. var gamepad = evt.gamepad;
  66027. if (gamepad.index in _this._babylonGamepads) {
  66028. if (_this._babylonGamepads[gamepad.index].isConnected) {
  66029. return;
  66030. }
  66031. }
  66032. var newGamepad;
  66033. if (_this._babylonGamepads[gamepad.index]) {
  66034. newGamepad = _this._babylonGamepads[gamepad.index];
  66035. newGamepad.browserGamepad = gamepad;
  66036. newGamepad._isConnected = true;
  66037. }
  66038. else {
  66039. newGamepad = _this._addNewGamepad(gamepad);
  66040. }
  66041. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66042. _this._startMonitoringGamepads();
  66043. };
  66044. this._onGamepadDisconnectedEvent = function (evt) {
  66045. var gamepad = evt.gamepad;
  66046. // Remove the gamepad from the list of gamepads to monitor.
  66047. for (var i in _this._babylonGamepads) {
  66048. if (_this._babylonGamepads[i].index === gamepad.index) {
  66049. var disconnectedGamepad = _this._babylonGamepads[i];
  66050. disconnectedGamepad._isConnected = false;
  66051. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  66052. break;
  66053. }
  66054. }
  66055. };
  66056. if (this._gamepadSupport) {
  66057. //first add already-connected gamepads
  66058. this._updateGamepadObjects();
  66059. if (this._babylonGamepads.length) {
  66060. this._startMonitoringGamepads();
  66061. }
  66062. // Checking if the gamepad connected event is supported (like in Firefox)
  66063. if (this._gamepadEventSupported) {
  66064. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66065. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66066. }
  66067. else {
  66068. this._startMonitoringGamepads();
  66069. }
  66070. }
  66071. }
  66072. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66073. get: function () {
  66074. return this._babylonGamepads;
  66075. },
  66076. enumerable: true,
  66077. configurable: true
  66078. });
  66079. GamepadManager.prototype.getGamepadByType = function (type) {
  66080. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66081. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66082. var gamepad = _a[_i];
  66083. if (gamepad && gamepad.type === type) {
  66084. return gamepad;
  66085. }
  66086. }
  66087. return null;
  66088. };
  66089. GamepadManager.prototype.dispose = function () {
  66090. if (this._gamepadEventSupported) {
  66091. if (this._onGamepadConnectedEvent) {
  66092. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66093. }
  66094. if (this._onGamepadDisconnectedEvent) {
  66095. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66096. }
  66097. this._onGamepadConnectedEvent = null;
  66098. this._onGamepadDisconnectedEvent = null;
  66099. }
  66100. this._babylonGamepads.forEach(function (gamepad) {
  66101. gamepad.dispose();
  66102. });
  66103. this.onGamepadConnectedObservable.clear();
  66104. this.onGamepadDisconnectedObservable.clear();
  66105. this._oneGamepadConnected = false;
  66106. this._stopMonitoringGamepads();
  66107. this._babylonGamepads = [];
  66108. };
  66109. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66110. if (!this._oneGamepadConnected) {
  66111. this._oneGamepadConnected = true;
  66112. }
  66113. var newGamepad;
  66114. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66115. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66116. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66117. }
  66118. else if (gamepad.pose) {
  66119. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66120. }
  66121. else {
  66122. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66123. }
  66124. this._babylonGamepads[newGamepad.index] = newGamepad;
  66125. return newGamepad;
  66126. };
  66127. GamepadManager.prototype._startMonitoringGamepads = function () {
  66128. if (!this._isMonitoring) {
  66129. this._isMonitoring = true;
  66130. //back-comp
  66131. if (!this._scene) {
  66132. this._checkGamepadsStatus();
  66133. }
  66134. }
  66135. };
  66136. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66137. this._isMonitoring = false;
  66138. };
  66139. GamepadManager.prototype._checkGamepadsStatus = function () {
  66140. var _this = this;
  66141. // Hack to be compatible Chrome
  66142. this._updateGamepadObjects();
  66143. for (var i in this._babylonGamepads) {
  66144. var gamepad = this._babylonGamepads[i];
  66145. if (!gamepad || !gamepad.isConnected) {
  66146. continue;
  66147. }
  66148. gamepad.update();
  66149. }
  66150. if (this._isMonitoring && !this._scene) {
  66151. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66152. }
  66153. };
  66154. // This function is called only on Chrome, which does not properly support
  66155. // connection/disconnection events and forces you to recopy again the gamepad object
  66156. GamepadManager.prototype._updateGamepadObjects = function () {
  66157. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66158. for (var i = 0; i < gamepads.length; i++) {
  66159. if (gamepads[i]) {
  66160. if (!this._babylonGamepads[gamepads[i].index]) {
  66161. var newGamepad = this._addNewGamepad(gamepads[i]);
  66162. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66163. }
  66164. else {
  66165. // Forced to copy again this object for Chrome for unknown reason
  66166. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66167. if (!this._babylonGamepads[i].isConnected) {
  66168. this._babylonGamepads[i]._isConnected = true;
  66169. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66170. }
  66171. }
  66172. }
  66173. }
  66174. };
  66175. return GamepadManager;
  66176. }());
  66177. BABYLON.GamepadManager = GamepadManager;
  66178. })(BABYLON || (BABYLON = {}));
  66179. //# sourceMappingURL=babylon.gamepadManager.js.map
  66180. "use strict";
  66181. var BABYLON;
  66182. (function (BABYLON) {
  66183. var StickValues = /** @class */ (function () {
  66184. function StickValues(x, y) {
  66185. this.x = x;
  66186. this.y = y;
  66187. }
  66188. return StickValues;
  66189. }());
  66190. BABYLON.StickValues = StickValues;
  66191. var Gamepad = /** @class */ (function () {
  66192. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66193. if (leftStickX === void 0) { leftStickX = 0; }
  66194. if (leftStickY === void 0) { leftStickY = 1; }
  66195. if (rightStickX === void 0) { rightStickX = 2; }
  66196. if (rightStickY === void 0) { rightStickY = 3; }
  66197. this.id = id;
  66198. this.index = index;
  66199. this.browserGamepad = browserGamepad;
  66200. this._isConnected = true;
  66201. this._invertLeftStickY = false;
  66202. this.type = Gamepad.GAMEPAD;
  66203. this._leftStickAxisX = leftStickX;
  66204. this._leftStickAxisY = leftStickY;
  66205. this._rightStickAxisX = rightStickX;
  66206. this._rightStickAxisY = rightStickY;
  66207. if (this.browserGamepad.axes.length >= 2) {
  66208. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66209. }
  66210. if (this.browserGamepad.axes.length >= 4) {
  66211. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66212. }
  66213. }
  66214. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66215. get: function () {
  66216. return this._isConnected;
  66217. },
  66218. enumerable: true,
  66219. configurable: true
  66220. });
  66221. Gamepad.prototype.onleftstickchanged = function (callback) {
  66222. this._onleftstickchanged = callback;
  66223. };
  66224. Gamepad.prototype.onrightstickchanged = function (callback) {
  66225. this._onrightstickchanged = callback;
  66226. };
  66227. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66228. get: function () {
  66229. return this._leftStick;
  66230. },
  66231. set: function (newValues) {
  66232. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66233. this._onleftstickchanged(newValues);
  66234. }
  66235. this._leftStick = newValues;
  66236. },
  66237. enumerable: true,
  66238. configurable: true
  66239. });
  66240. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66241. get: function () {
  66242. return this._rightStick;
  66243. },
  66244. set: function (newValues) {
  66245. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66246. this._onrightstickchanged(newValues);
  66247. }
  66248. this._rightStick = newValues;
  66249. },
  66250. enumerable: true,
  66251. configurable: true
  66252. });
  66253. Gamepad.prototype.update = function () {
  66254. if (this._leftStick) {
  66255. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66256. if (this._invertLeftStickY) {
  66257. this.leftStick.y *= -1;
  66258. }
  66259. }
  66260. if (this._rightStick) {
  66261. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66262. }
  66263. };
  66264. Gamepad.prototype.dispose = function () {
  66265. };
  66266. Gamepad.GAMEPAD = 0;
  66267. Gamepad.GENERIC = 1;
  66268. Gamepad.XBOX = 2;
  66269. Gamepad.POSE_ENABLED = 3;
  66270. return Gamepad;
  66271. }());
  66272. BABYLON.Gamepad = Gamepad;
  66273. var GenericPad = /** @class */ (function (_super) {
  66274. __extends(GenericPad, _super);
  66275. function GenericPad(id, index, browserGamepad) {
  66276. var _this = _super.call(this, id, index, browserGamepad) || this;
  66277. _this.onButtonDownObservable = new BABYLON.Observable();
  66278. _this.onButtonUpObservable = new BABYLON.Observable();
  66279. _this.type = Gamepad.GENERIC;
  66280. _this._buttons = new Array(browserGamepad.buttons.length);
  66281. return _this;
  66282. }
  66283. GenericPad.prototype.onbuttondown = function (callback) {
  66284. this._onbuttondown = callback;
  66285. };
  66286. GenericPad.prototype.onbuttonup = function (callback) {
  66287. this._onbuttonup = callback;
  66288. };
  66289. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66290. if (newValue !== currentValue) {
  66291. if (newValue === 1) {
  66292. if (this._onbuttondown) {
  66293. this._onbuttondown(buttonIndex);
  66294. }
  66295. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66296. }
  66297. if (newValue === 0) {
  66298. if (this._onbuttonup) {
  66299. this._onbuttonup(buttonIndex);
  66300. }
  66301. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66302. }
  66303. }
  66304. return newValue;
  66305. };
  66306. GenericPad.prototype.update = function () {
  66307. _super.prototype.update.call(this);
  66308. for (var index = 0; index < this._buttons.length; index++) {
  66309. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66310. }
  66311. };
  66312. GenericPad.prototype.dispose = function () {
  66313. _super.prototype.dispose.call(this);
  66314. this.onButtonDownObservable.clear();
  66315. this.onButtonUpObservable.clear();
  66316. };
  66317. return GenericPad;
  66318. }(Gamepad));
  66319. BABYLON.GenericPad = GenericPad;
  66320. })(BABYLON || (BABYLON = {}));
  66321. //# sourceMappingURL=babylon.gamepad.js.map
  66322. "use strict";
  66323. var BABYLON;
  66324. (function (BABYLON) {
  66325. var Xbox360Button;
  66326. (function (Xbox360Button) {
  66327. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66328. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66329. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66330. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66331. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66332. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66333. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66334. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66335. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66336. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66337. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66338. var Xbox360Dpad;
  66339. (function (Xbox360Dpad) {
  66340. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66341. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66342. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66343. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66344. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66345. var Xbox360Pad = /** @class */ (function (_super) {
  66346. __extends(Xbox360Pad, _super);
  66347. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66348. if (xboxOne === void 0) { xboxOne = false; }
  66349. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66350. _this._leftTrigger = 0;
  66351. _this._rightTrigger = 0;
  66352. _this.onButtonDownObservable = new BABYLON.Observable();
  66353. _this.onButtonUpObservable = new BABYLON.Observable();
  66354. _this.onPadDownObservable = new BABYLON.Observable();
  66355. _this.onPadUpObservable = new BABYLON.Observable();
  66356. _this._buttonA = 0;
  66357. _this._buttonB = 0;
  66358. _this._buttonX = 0;
  66359. _this._buttonY = 0;
  66360. _this._buttonBack = 0;
  66361. _this._buttonStart = 0;
  66362. _this._buttonLB = 0;
  66363. _this._buttonRB = 0;
  66364. _this._buttonLeftStick = 0;
  66365. _this._buttonRightStick = 0;
  66366. _this._dPadUp = 0;
  66367. _this._dPadDown = 0;
  66368. _this._dPadLeft = 0;
  66369. _this._dPadRight = 0;
  66370. _this._isXboxOnePad = false;
  66371. _this.type = BABYLON.Gamepad.XBOX;
  66372. _this._isXboxOnePad = xboxOne;
  66373. return _this;
  66374. }
  66375. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66376. this._onlefttriggerchanged = callback;
  66377. };
  66378. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66379. this._onrighttriggerchanged = callback;
  66380. };
  66381. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66382. get: function () {
  66383. return this._leftTrigger;
  66384. },
  66385. set: function (newValue) {
  66386. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66387. this._onlefttriggerchanged(newValue);
  66388. }
  66389. this._leftTrigger = newValue;
  66390. },
  66391. enumerable: true,
  66392. configurable: true
  66393. });
  66394. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66395. get: function () {
  66396. return this._rightTrigger;
  66397. },
  66398. set: function (newValue) {
  66399. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66400. this._onrighttriggerchanged(newValue);
  66401. }
  66402. this._rightTrigger = newValue;
  66403. },
  66404. enumerable: true,
  66405. configurable: true
  66406. });
  66407. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66408. this._onbuttondown = callback;
  66409. };
  66410. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66411. this._onbuttonup = callback;
  66412. };
  66413. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66414. this._ondpaddown = callback;
  66415. };
  66416. Xbox360Pad.prototype.ondpadup = function (callback) {
  66417. this._ondpadup = callback;
  66418. };
  66419. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66420. if (newValue !== currentValue) {
  66421. if (newValue === 1) {
  66422. if (this._onbuttondown) {
  66423. this._onbuttondown(buttonType);
  66424. }
  66425. this.onButtonDownObservable.notifyObservers(buttonType);
  66426. }
  66427. if (newValue === 0) {
  66428. if (this._onbuttonup) {
  66429. this._onbuttonup(buttonType);
  66430. }
  66431. this.onButtonUpObservable.notifyObservers(buttonType);
  66432. }
  66433. }
  66434. return newValue;
  66435. };
  66436. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66437. if (newValue !== currentValue) {
  66438. if (newValue === 1) {
  66439. if (this._ondpaddown) {
  66440. this._ondpaddown(buttonType);
  66441. }
  66442. this.onPadDownObservable.notifyObservers(buttonType);
  66443. }
  66444. if (newValue === 0) {
  66445. if (this._ondpadup) {
  66446. this._ondpadup(buttonType);
  66447. }
  66448. this.onPadUpObservable.notifyObservers(buttonType);
  66449. }
  66450. }
  66451. return newValue;
  66452. };
  66453. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66454. get: function () {
  66455. return this._buttonA;
  66456. },
  66457. set: function (value) {
  66458. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66459. },
  66460. enumerable: true,
  66461. configurable: true
  66462. });
  66463. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66464. get: function () {
  66465. return this._buttonB;
  66466. },
  66467. set: function (value) {
  66468. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66469. },
  66470. enumerable: true,
  66471. configurable: true
  66472. });
  66473. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66474. get: function () {
  66475. return this._buttonX;
  66476. },
  66477. set: function (value) {
  66478. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66479. },
  66480. enumerable: true,
  66481. configurable: true
  66482. });
  66483. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66484. get: function () {
  66485. return this._buttonY;
  66486. },
  66487. set: function (value) {
  66488. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66489. },
  66490. enumerable: true,
  66491. configurable: true
  66492. });
  66493. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66494. get: function () {
  66495. return this._buttonStart;
  66496. },
  66497. set: function (value) {
  66498. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66499. },
  66500. enumerable: true,
  66501. configurable: true
  66502. });
  66503. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66504. get: function () {
  66505. return this._buttonBack;
  66506. },
  66507. set: function (value) {
  66508. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66509. },
  66510. enumerable: true,
  66511. configurable: true
  66512. });
  66513. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66514. get: function () {
  66515. return this._buttonLB;
  66516. },
  66517. set: function (value) {
  66518. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66519. },
  66520. enumerable: true,
  66521. configurable: true
  66522. });
  66523. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66524. get: function () {
  66525. return this._buttonRB;
  66526. },
  66527. set: function (value) {
  66528. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66529. },
  66530. enumerable: true,
  66531. configurable: true
  66532. });
  66533. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66534. get: function () {
  66535. return this._buttonLeftStick;
  66536. },
  66537. set: function (value) {
  66538. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66539. },
  66540. enumerable: true,
  66541. configurable: true
  66542. });
  66543. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66544. get: function () {
  66545. return this._buttonRightStick;
  66546. },
  66547. set: function (value) {
  66548. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66549. },
  66550. enumerable: true,
  66551. configurable: true
  66552. });
  66553. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66554. get: function () {
  66555. return this._dPadUp;
  66556. },
  66557. set: function (value) {
  66558. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66559. },
  66560. enumerable: true,
  66561. configurable: true
  66562. });
  66563. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66564. get: function () {
  66565. return this._dPadDown;
  66566. },
  66567. set: function (value) {
  66568. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66569. },
  66570. enumerable: true,
  66571. configurable: true
  66572. });
  66573. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66574. get: function () {
  66575. return this._dPadLeft;
  66576. },
  66577. set: function (value) {
  66578. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66584. get: function () {
  66585. return this._dPadRight;
  66586. },
  66587. set: function (value) {
  66588. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66589. },
  66590. enumerable: true,
  66591. configurable: true
  66592. });
  66593. Xbox360Pad.prototype.update = function () {
  66594. _super.prototype.update.call(this);
  66595. if (this._isXboxOnePad) {
  66596. this.buttonA = this.browserGamepad.buttons[0].value;
  66597. this.buttonB = this.browserGamepad.buttons[1].value;
  66598. this.buttonX = this.browserGamepad.buttons[2].value;
  66599. this.buttonY = this.browserGamepad.buttons[3].value;
  66600. this.buttonLB = this.browserGamepad.buttons[4].value;
  66601. this.buttonRB = this.browserGamepad.buttons[5].value;
  66602. this.leftTrigger = this.browserGamepad.axes[2];
  66603. this.rightTrigger = this.browserGamepad.axes[5];
  66604. this.buttonBack = this.browserGamepad.buttons[9].value;
  66605. this.buttonStart = this.browserGamepad.buttons[8].value;
  66606. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66607. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66608. this.dPadUp = this.browserGamepad.buttons[11].value;
  66609. this.dPadDown = this.browserGamepad.buttons[12].value;
  66610. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66611. this.dPadRight = this.browserGamepad.buttons[14].value;
  66612. }
  66613. else {
  66614. this.buttonA = this.browserGamepad.buttons[0].value;
  66615. this.buttonB = this.browserGamepad.buttons[1].value;
  66616. this.buttonX = this.browserGamepad.buttons[2].value;
  66617. this.buttonY = this.browserGamepad.buttons[3].value;
  66618. this.buttonLB = this.browserGamepad.buttons[4].value;
  66619. this.buttonRB = this.browserGamepad.buttons[5].value;
  66620. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66621. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66622. this.buttonBack = this.browserGamepad.buttons[8].value;
  66623. this.buttonStart = this.browserGamepad.buttons[9].value;
  66624. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66625. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66626. this.dPadUp = this.browserGamepad.buttons[12].value;
  66627. this.dPadDown = this.browserGamepad.buttons[13].value;
  66628. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66629. this.dPadRight = this.browserGamepad.buttons[15].value;
  66630. }
  66631. };
  66632. Xbox360Pad.prototype.dispose = function () {
  66633. _super.prototype.dispose.call(this);
  66634. this.onButtonDownObservable.clear();
  66635. this.onButtonUpObservable.clear();
  66636. this.onPadDownObservable.clear();
  66637. this.onPadUpObservable.clear();
  66638. };
  66639. return Xbox360Pad;
  66640. }(BABYLON.Gamepad));
  66641. BABYLON.Xbox360Pad = Xbox360Pad;
  66642. })(BABYLON || (BABYLON = {}));
  66643. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66644. "use strict";
  66645. var BABYLON;
  66646. (function (BABYLON) {
  66647. var PoseEnabledControllerType;
  66648. (function (PoseEnabledControllerType) {
  66649. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66650. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66651. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66652. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66653. /**
  66654. * Google Daydream
  66655. */
  66656. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66657. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66658. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66659. var PoseEnabledControllerHelper = /** @class */ (function () {
  66660. function PoseEnabledControllerHelper() {
  66661. }
  66662. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66663. // Oculus Touch
  66664. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66665. return new BABYLON.OculusTouchController(vrGamepad);
  66666. }
  66667. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66668. return new BABYLON.WindowsMotionController(vrGamepad);
  66669. }
  66670. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66671. return new BABYLON.ViveController(vrGamepad);
  66672. }
  66673. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66674. return new BABYLON.GearVRController(vrGamepad);
  66675. }
  66676. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66677. return new BABYLON.DaydreamController(vrGamepad);
  66678. }
  66679. else {
  66680. return new BABYLON.GenericController(vrGamepad);
  66681. }
  66682. };
  66683. return PoseEnabledControllerHelper;
  66684. }());
  66685. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66686. var PoseEnabledController = /** @class */ (function (_super) {
  66687. __extends(PoseEnabledController, _super);
  66688. function PoseEnabledController(browserGamepad) {
  66689. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66690. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66691. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66692. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66693. // Represents device position and rotation in babylon space
  66694. _this.devicePosition = BABYLON.Vector3.Zero();
  66695. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66696. _this.deviceScaleFactor = 1;
  66697. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66698. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66699. /**
  66700. * Node to be used when casting a ray from the controller
  66701. */
  66702. _this._pointingPoseNode = null;
  66703. _this._workingMatrix = BABYLON.Matrix.Identity();
  66704. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66705. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66706. _this.position = BABYLON.Vector3.Zero();
  66707. _this.rotationQuaternion = new BABYLON.Quaternion();
  66708. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66709. _this._calculatedRotation = new BABYLON.Quaternion();
  66710. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66711. return _this;
  66712. }
  66713. PoseEnabledController.prototype.update = function () {
  66714. _super.prototype.update.call(this);
  66715. var pose = this.browserGamepad.pose;
  66716. this.updateFromDevice(pose);
  66717. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66718. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66719. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66720. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66721. if (this._mesh) {
  66722. this._mesh.position.copyFrom(this.devicePosition);
  66723. if (this._mesh.rotationQuaternion) {
  66724. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66725. }
  66726. }
  66727. };
  66728. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66729. if (poseData) {
  66730. this.rawPose = poseData;
  66731. if (poseData.position) {
  66732. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66733. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66734. this._deviceRoomPosition.z *= -1;
  66735. }
  66736. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66737. this._calculatedPosition.addInPlace(this.position);
  66738. }
  66739. var pose = this.rawPose;
  66740. if (poseData.orientation && pose.orientation) {
  66741. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66742. if (this._mesh) {
  66743. if (this._mesh.getScene().useRightHandedSystem) {
  66744. this._deviceRoomRotationQuaternion.z *= -1;
  66745. this._deviceRoomRotationQuaternion.w *= -1;
  66746. }
  66747. else {
  66748. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66749. }
  66750. }
  66751. // if the camera is set, rotate to the camera's rotation
  66752. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66753. }
  66754. }
  66755. };
  66756. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66757. if (this._mesh) {
  66758. this._mesh.parent = null;
  66759. }
  66760. this._mesh = mesh;
  66761. if (this._poseControlledCamera) {
  66762. this._mesh.parent = this._poseControlledCamera;
  66763. }
  66764. if (!this._mesh.rotationQuaternion) {
  66765. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66766. }
  66767. };
  66768. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66769. this._poseControlledCamera = camera;
  66770. if (this._mesh) {
  66771. this._mesh.parent = this._poseControlledCamera;
  66772. }
  66773. };
  66774. PoseEnabledController.prototype.dispose = function () {
  66775. if (this._mesh) {
  66776. this._mesh.dispose();
  66777. }
  66778. this._mesh = null;
  66779. _super.prototype.dispose.call(this);
  66780. };
  66781. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66782. get: function () {
  66783. return this._mesh;
  66784. },
  66785. enumerable: true,
  66786. configurable: true
  66787. });
  66788. PoseEnabledController.prototype.getForwardRay = function (length) {
  66789. if (length === void 0) { length = 100; }
  66790. if (!this.mesh) {
  66791. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66792. }
  66793. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66794. var origin = m.getTranslation();
  66795. var forward = new BABYLON.Vector3(0, 0, -1);
  66796. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66797. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66798. return new BABYLON.Ray(origin, direction, length);
  66799. };
  66800. /**
  66801. * Name of the child mesh that can be used to cast a ray from the controller
  66802. */
  66803. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66804. return PoseEnabledController;
  66805. }(BABYLON.Gamepad));
  66806. BABYLON.PoseEnabledController = PoseEnabledController;
  66807. })(BABYLON || (BABYLON = {}));
  66808. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66809. "use strict";
  66810. var BABYLON;
  66811. (function (BABYLON) {
  66812. var WebVRController = /** @class */ (function (_super) {
  66813. __extends(WebVRController, _super);
  66814. function WebVRController(vrGamepad) {
  66815. var _this = _super.call(this, vrGamepad) || this;
  66816. // Observables
  66817. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66818. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66819. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66820. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66821. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66822. _this.pad = { x: 0, y: 0 };
  66823. // avoid GC, store state in a tmp object
  66824. _this._changes = {
  66825. pressChanged: false,
  66826. touchChanged: false,
  66827. valueChanged: false,
  66828. changed: false
  66829. };
  66830. _this._buttons = new Array(vrGamepad.buttons.length);
  66831. _this.hand = vrGamepad.hand;
  66832. return _this;
  66833. }
  66834. WebVRController.prototype.onButtonStateChange = function (callback) {
  66835. this._onButtonStateChange = callback;
  66836. };
  66837. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66838. get: function () {
  66839. return this._defaultModel;
  66840. },
  66841. enumerable: true,
  66842. configurable: true
  66843. });
  66844. WebVRController.prototype.update = function () {
  66845. _super.prototype.update.call(this);
  66846. for (var index = 0; index < this._buttons.length; index++) {
  66847. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66848. }
  66849. ;
  66850. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66851. this.pad.x = this.leftStick.x;
  66852. this.pad.y = this.leftStick.y;
  66853. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66854. }
  66855. };
  66856. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66857. if (!newState) {
  66858. newState = {
  66859. pressed: false,
  66860. touched: false,
  66861. value: 0
  66862. };
  66863. }
  66864. if (!currentState) {
  66865. this._buttons[buttonIndex] = {
  66866. pressed: newState.pressed,
  66867. touched: newState.touched,
  66868. value: newState.value
  66869. };
  66870. return;
  66871. }
  66872. this._checkChanges(newState, currentState);
  66873. if (this._changes.changed) {
  66874. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66875. this._handleButtonChange(buttonIndex, newState, this._changes);
  66876. }
  66877. this._buttons[buttonIndex].pressed = newState.pressed;
  66878. this._buttons[buttonIndex].touched = newState.touched;
  66879. // oculus triggers are never 0, thou not touched.
  66880. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66881. };
  66882. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66883. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66884. this._changes.touchChanged = newState.touched !== currentState.touched;
  66885. this._changes.valueChanged = newState.value !== currentState.value;
  66886. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66887. return this._changes;
  66888. };
  66889. WebVRController.prototype.dispose = function () {
  66890. _super.prototype.dispose.call(this);
  66891. this.onTriggerStateChangedObservable.clear();
  66892. this.onMainButtonStateChangedObservable.clear();
  66893. this.onSecondaryButtonStateChangedObservable.clear();
  66894. this.onPadStateChangedObservable.clear();
  66895. this.onPadValuesChangedObservable.clear();
  66896. };
  66897. return WebVRController;
  66898. }(BABYLON.PoseEnabledController));
  66899. BABYLON.WebVRController = WebVRController;
  66900. })(BABYLON || (BABYLON = {}));
  66901. //# sourceMappingURL=babylon.webVRController.js.map
  66902. "use strict";
  66903. var BABYLON;
  66904. (function (BABYLON) {
  66905. var OculusTouchController = /** @class */ (function (_super) {
  66906. __extends(OculusTouchController, _super);
  66907. function OculusTouchController(vrGamepad) {
  66908. var _this = _super.call(this, vrGamepad) || this;
  66909. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66910. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66911. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66912. return _this;
  66913. }
  66914. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66915. var _this = this;
  66916. var meshName;
  66917. // Hand
  66918. if (this.hand === 'left') {
  66919. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66920. }
  66921. else {
  66922. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66923. }
  66924. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66925. /*
  66926. Parent Mesh name: oculus_touch_left
  66927. - body
  66928. - trigger
  66929. - thumbstick
  66930. - grip
  66931. - button_y
  66932. - button_x
  66933. - button_enter
  66934. */
  66935. _this._defaultModel = newMeshes[1];
  66936. _this.attachToMesh(_this._defaultModel);
  66937. if (meshLoaded) {
  66938. meshLoaded(_this._defaultModel);
  66939. }
  66940. });
  66941. };
  66942. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66943. // helper getters for left and right hand.
  66944. get: function () {
  66945. if (this.hand === 'right') {
  66946. return this.onMainButtonStateChangedObservable;
  66947. }
  66948. else {
  66949. throw new Error('No A button on left hand');
  66950. }
  66951. },
  66952. enumerable: true,
  66953. configurable: true
  66954. });
  66955. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66956. get: function () {
  66957. if (this.hand === 'right') {
  66958. return this.onSecondaryButtonStateChangedObservable;
  66959. }
  66960. else {
  66961. throw new Error('No B button on left hand');
  66962. }
  66963. },
  66964. enumerable: true,
  66965. configurable: true
  66966. });
  66967. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66968. get: function () {
  66969. if (this.hand === 'left') {
  66970. return this.onMainButtonStateChangedObservable;
  66971. }
  66972. else {
  66973. throw new Error('No X button on right hand');
  66974. }
  66975. },
  66976. enumerable: true,
  66977. configurable: true
  66978. });
  66979. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66980. get: function () {
  66981. if (this.hand === 'left') {
  66982. return this.onSecondaryButtonStateChangedObservable;
  66983. }
  66984. else {
  66985. throw new Error('No Y button on right hand');
  66986. }
  66987. },
  66988. enumerable: true,
  66989. configurable: true
  66990. });
  66991. /*
  66992. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66993. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66994. 2) secondary trigger (same)
  66995. 3) A (right) X (left), touch, pressed = value
  66996. 4) B / Y
  66997. 5) thumb rest
  66998. */
  66999. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67000. var notifyObject = state; //{ state: state, changes: changes };
  67001. var triggerDirection = this.hand === 'right' ? -1 : 1;
  67002. switch (buttonIdx) {
  67003. case 0:
  67004. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67005. return;
  67006. case 1:// index trigger
  67007. if (this._defaultModel) {
  67008. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  67009. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  67010. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  67011. }
  67012. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67013. return;
  67014. case 2:// secondary trigger
  67015. if (this._defaultModel) {
  67016. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  67017. }
  67018. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  67019. return;
  67020. case 3:
  67021. if (this._defaultModel) {
  67022. if (notifyObject.pressed) {
  67023. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  67024. }
  67025. else {
  67026. (this._defaultModel.getChildren()[1]).position.y = 0;
  67027. }
  67028. }
  67029. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67030. return;
  67031. case 4:
  67032. if (this._defaultModel) {
  67033. if (notifyObject.pressed) {
  67034. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67035. }
  67036. else {
  67037. (this._defaultModel.getChildren()[2]).position.y = 0;
  67038. }
  67039. }
  67040. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67041. return;
  67042. case 5:
  67043. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  67044. return;
  67045. }
  67046. };
  67047. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  67048. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  67049. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  67050. return OculusTouchController;
  67051. }(BABYLON.WebVRController));
  67052. BABYLON.OculusTouchController = OculusTouchController;
  67053. })(BABYLON || (BABYLON = {}));
  67054. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67055. "use strict";
  67056. var BABYLON;
  67057. (function (BABYLON) {
  67058. var ViveController = /** @class */ (function (_super) {
  67059. __extends(ViveController, _super);
  67060. function ViveController(vrGamepad) {
  67061. var _this = _super.call(this, vrGamepad) || this;
  67062. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67063. _this._invertLeftStickY = true;
  67064. return _this;
  67065. }
  67066. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67067. var _this = this;
  67068. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67069. /*
  67070. Parent Mesh name: ViveWand
  67071. - body
  67072. - r_gripper
  67073. - l_gripper
  67074. - menu_button
  67075. - system_button
  67076. - trackpad
  67077. - trigger
  67078. - LED
  67079. */
  67080. _this._defaultModel = newMeshes[1];
  67081. _this.attachToMesh(_this._defaultModel);
  67082. if (meshLoaded) {
  67083. meshLoaded(_this._defaultModel);
  67084. }
  67085. });
  67086. };
  67087. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67088. get: function () {
  67089. return this.onMainButtonStateChangedObservable;
  67090. },
  67091. enumerable: true,
  67092. configurable: true
  67093. });
  67094. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67095. get: function () {
  67096. return this.onMainButtonStateChangedObservable;
  67097. },
  67098. enumerable: true,
  67099. configurable: true
  67100. });
  67101. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67102. get: function () {
  67103. return this.onSecondaryButtonStateChangedObservable;
  67104. },
  67105. enumerable: true,
  67106. configurable: true
  67107. });
  67108. /**
  67109. * Vive mapping:
  67110. * 0: touchpad
  67111. * 1: trigger
  67112. * 2: left AND right buttons
  67113. * 3: menu button
  67114. */
  67115. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67116. var notifyObject = state; //{ state: state, changes: changes };
  67117. switch (buttonIdx) {
  67118. case 0:
  67119. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67120. return;
  67121. case 1:// index trigger
  67122. if (this._defaultModel) {
  67123. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67124. }
  67125. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67126. return;
  67127. case 2:// left AND right button
  67128. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67129. return;
  67130. case 3:
  67131. if (this._defaultModel) {
  67132. if (notifyObject.pressed) {
  67133. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67134. }
  67135. else {
  67136. (this._defaultModel.getChildren()[2]).position.y = 0;
  67137. }
  67138. }
  67139. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67140. return;
  67141. }
  67142. };
  67143. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67144. ViveController.MODEL_FILENAME = 'wand.babylon';
  67145. return ViveController;
  67146. }(BABYLON.WebVRController));
  67147. BABYLON.ViveController = ViveController;
  67148. })(BABYLON || (BABYLON = {}));
  67149. //# sourceMappingURL=babylon.viveController.js.map
  67150. "use strict";
  67151. var BABYLON;
  67152. (function (BABYLON) {
  67153. var GenericController = /** @class */ (function (_super) {
  67154. __extends(GenericController, _super);
  67155. function GenericController(vrGamepad) {
  67156. return _super.call(this, vrGamepad) || this;
  67157. }
  67158. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67159. var _this = this;
  67160. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67161. _this._defaultModel = newMeshes[1];
  67162. _this.attachToMesh(_this._defaultModel);
  67163. if (meshLoaded) {
  67164. meshLoaded(_this._defaultModel);
  67165. }
  67166. });
  67167. };
  67168. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67169. console.log("Button id: " + buttonIdx + "state: ");
  67170. console.dir(state);
  67171. };
  67172. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67173. GenericController.MODEL_FILENAME = 'generic.babylon';
  67174. return GenericController;
  67175. }(BABYLON.WebVRController));
  67176. BABYLON.GenericController = GenericController;
  67177. })(BABYLON || (BABYLON = {}));
  67178. //# sourceMappingURL=babylon.genericController.js.map
  67179. "use strict";
  67180. var BABYLON;
  67181. (function (BABYLON) {
  67182. var LoadedMeshInfo = /** @class */ (function () {
  67183. function LoadedMeshInfo() {
  67184. this.buttonMeshes = {};
  67185. this.axisMeshes = {};
  67186. }
  67187. return LoadedMeshInfo;
  67188. }());
  67189. var WindowsMotionController = /** @class */ (function (_super) {
  67190. __extends(WindowsMotionController, _super);
  67191. function WindowsMotionController(vrGamepad) {
  67192. var _this = _super.call(this, vrGamepad) || this;
  67193. _this._mapping = {
  67194. // Semantic button names
  67195. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67196. // A mapping of the button name to glTF model node name
  67197. // that should be transformed by button value.
  67198. buttonMeshNames: {
  67199. 'trigger': 'SELECT',
  67200. 'menu': 'MENU',
  67201. 'grip': 'GRASP',
  67202. 'thumbstick': 'THUMBSTICK_PRESS',
  67203. 'trackpad': 'TOUCHPAD_PRESS'
  67204. },
  67205. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67206. buttonObservableNames: {
  67207. 'trigger': 'onTriggerStateChangedObservable',
  67208. 'menu': 'onSecondaryButtonStateChangedObservable',
  67209. 'grip': 'onMainButtonStateChangedObservable',
  67210. 'thumbstick': 'onPadStateChangedObservable',
  67211. 'trackpad': 'onTrackpadChangedObservable'
  67212. },
  67213. // A mapping of the axis name to glTF model node name
  67214. // that should be transformed by axis value.
  67215. // This array mirrors the browserGamepad.axes array, such that
  67216. // the mesh corresponding to axis 0 is in this array index 0.
  67217. axisMeshNames: [
  67218. 'THUMBSTICK_X',
  67219. 'THUMBSTICK_Y',
  67220. 'TOUCHPAD_TOUCH_X',
  67221. 'TOUCHPAD_TOUCH_Y'
  67222. ],
  67223. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67224. };
  67225. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67226. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67227. _this.trackpad = { x: 0, y: 0 };
  67228. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67229. _this._loadedMeshInfo = null;
  67230. return _this;
  67231. }
  67232. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67233. get: function () {
  67234. return this.onTriggerStateChangedObservable;
  67235. },
  67236. enumerable: true,
  67237. configurable: true
  67238. });
  67239. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67240. get: function () {
  67241. return this.onSecondaryButtonStateChangedObservable;
  67242. },
  67243. enumerable: true,
  67244. configurable: true
  67245. });
  67246. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67247. get: function () {
  67248. return this.onMainButtonStateChangedObservable;
  67249. },
  67250. enumerable: true,
  67251. configurable: true
  67252. });
  67253. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67254. get: function () {
  67255. return this.onPadStateChangedObservable;
  67256. },
  67257. enumerable: true,
  67258. configurable: true
  67259. });
  67260. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67261. get: function () {
  67262. return this.onTrackpadChangedObservable;
  67263. },
  67264. enumerable: true,
  67265. configurable: true
  67266. });
  67267. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67268. get: function () {
  67269. return this.onTrackpadValuesChangedObservable;
  67270. },
  67271. enumerable: true,
  67272. configurable: true
  67273. });
  67274. /**
  67275. * Called once per frame by the engine.
  67276. */
  67277. WindowsMotionController.prototype.update = function () {
  67278. _super.prototype.update.call(this);
  67279. if (this.browserGamepad.axes) {
  67280. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67281. this.trackpad.x = this.browserGamepad["axes"][2];
  67282. this.trackpad.y = this.browserGamepad["axes"][3];
  67283. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67284. }
  67285. // Only need to animate axes if there is a loaded mesh
  67286. if (this._loadedMeshInfo) {
  67287. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67288. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67289. }
  67290. }
  67291. }
  67292. };
  67293. /**
  67294. * Called once for each button that changed state since the last frame
  67295. * @param buttonIdx Which button index changed
  67296. * @param state New state of the button
  67297. * @param changes Which properties on the state changed since last frame
  67298. */
  67299. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67300. var buttonName = this._mapping.buttons[buttonIdx];
  67301. if (!buttonName) {
  67302. return;
  67303. }
  67304. // Only emit events for buttons that we know how to map from index to name
  67305. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67306. if (observable) {
  67307. observable.notifyObservers(state);
  67308. }
  67309. this.lerpButtonTransform(buttonName, state.value);
  67310. };
  67311. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67312. // If there is no loaded mesh, there is nothing to transform.
  67313. if (!this._loadedMeshInfo) {
  67314. return;
  67315. }
  67316. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67317. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67318. return;
  67319. }
  67320. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67321. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67322. };
  67323. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67324. if (!this._loadedMeshInfo) {
  67325. return;
  67326. }
  67327. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67328. if (!meshInfo) {
  67329. return;
  67330. }
  67331. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67332. return;
  67333. }
  67334. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67335. var lerpValue = axisValue * 0.5 + 0.5;
  67336. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67337. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67338. };
  67339. /**
  67340. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67341. * @param scene scene in which to add meshes
  67342. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67343. */
  67344. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67345. var _this = this;
  67346. if (forceDefault === void 0) { forceDefault = false; }
  67347. var path;
  67348. var filename;
  67349. // Checking if GLB loader is present
  67350. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67351. // Determine the device specific folder based on the ID suffix
  67352. var device = 'default';
  67353. if (this.id && !forceDefault) {
  67354. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67355. device = ((match && match[0]) || device);
  67356. }
  67357. // Hand
  67358. if (this.hand === 'left') {
  67359. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67360. }
  67361. else {
  67362. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67363. }
  67364. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67365. }
  67366. else {
  67367. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67368. path = BABYLON.GenericController.MODEL_BASE_URL;
  67369. filename = BABYLON.GenericController.MODEL_FILENAME;
  67370. }
  67371. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67372. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67373. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67374. if (!_this._loadedMeshInfo) {
  67375. return;
  67376. }
  67377. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67378. _this.attachToMesh(_this._defaultModel);
  67379. if (meshLoaded) {
  67380. meshLoaded(_this._defaultModel);
  67381. }
  67382. }, null, function (scene, message) {
  67383. BABYLON.Tools.Log(message);
  67384. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67385. if (!forceDefault) {
  67386. _this.initControllerMesh(scene, meshLoaded, true);
  67387. }
  67388. });
  67389. };
  67390. /**
  67391. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67392. * can be transformed by button presses and axes values, based on this._mapping.
  67393. *
  67394. * @param scene scene in which the meshes exist
  67395. * @param meshes list of meshes that make up the controller model to process
  67396. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67397. */
  67398. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67399. var loadedMeshInfo = null;
  67400. // Create a new mesh to contain the glTF hierarchy
  67401. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67402. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67403. var childMesh = null;
  67404. for (var i = 0; i < meshes.length; i++) {
  67405. var mesh = meshes[i];
  67406. if (!mesh.parent) {
  67407. // Exclude controller meshes from picking results
  67408. mesh.isPickable = false;
  67409. // Handle root node, attach to the new parentMesh
  67410. childMesh = mesh;
  67411. break;
  67412. }
  67413. }
  67414. if (childMesh) {
  67415. childMesh.setParent(parentMesh);
  67416. // Create our mesh info. Note that this method will always return non-null.
  67417. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67418. }
  67419. else {
  67420. BABYLON.Tools.Warn('Could not find root node in model file.');
  67421. }
  67422. return loadedMeshInfo;
  67423. };
  67424. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67425. var loadedMeshInfo = new LoadedMeshInfo();
  67426. var i;
  67427. loadedMeshInfo.rootNode = rootNode;
  67428. // Reset the caches
  67429. loadedMeshInfo.buttonMeshes = {};
  67430. loadedMeshInfo.axisMeshes = {};
  67431. // Button Meshes
  67432. for (i = 0; i < this._mapping.buttons.length; i++) {
  67433. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67434. if (!buttonMeshName) {
  67435. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67436. continue;
  67437. }
  67438. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67439. if (!buttonMesh) {
  67440. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67441. continue;
  67442. }
  67443. var buttonMeshInfo = {
  67444. index: i,
  67445. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67446. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67447. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67448. };
  67449. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67450. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67451. }
  67452. else {
  67453. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67454. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67455. '(VALUE: ' + !!buttonMeshInfo.value +
  67456. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67457. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67458. ')');
  67459. }
  67460. }
  67461. // Axis Meshes
  67462. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67463. var axisMeshName = this._mapping.axisMeshNames[i];
  67464. if (!axisMeshName) {
  67465. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67466. continue;
  67467. }
  67468. var axisMesh = getChildByName(rootNode, axisMeshName);
  67469. if (!axisMesh) {
  67470. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67471. continue;
  67472. }
  67473. var axisMeshInfo = {
  67474. index: i,
  67475. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67476. min: getImmediateChildByName(axisMesh, 'MIN'),
  67477. max: getImmediateChildByName(axisMesh, 'MAX')
  67478. };
  67479. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67480. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67481. }
  67482. else {
  67483. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67484. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67485. '(VALUE: ' + !!axisMeshInfo.value +
  67486. ', MIN: ' + !!axisMeshInfo.min +
  67487. ', MAX:' + !!axisMeshInfo.max +
  67488. ')');
  67489. }
  67490. }
  67491. // Pointing Ray
  67492. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67493. if (!loadedMeshInfo.pointingPoseNode) {
  67494. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67495. }
  67496. return loadedMeshInfo;
  67497. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67498. function getChildByName(node, name) {
  67499. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67500. }
  67501. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67502. function getImmediateChildByName(node, name) {
  67503. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67504. }
  67505. };
  67506. WindowsMotionController.prototype.getForwardRay = function (length) {
  67507. if (length === void 0) { length = 100; }
  67508. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67509. return _super.prototype.getForwardRay.call(this, length);
  67510. }
  67511. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67512. var origin = m.getTranslation();
  67513. var forward = new BABYLON.Vector3(0, 0, -1);
  67514. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67515. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67516. return new BABYLON.Ray(origin, direction, length);
  67517. };
  67518. WindowsMotionController.prototype.dispose = function () {
  67519. _super.prototype.dispose.call(this);
  67520. this.onTrackpadChangedObservable.clear();
  67521. };
  67522. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67523. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67524. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67525. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67526. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67527. return WindowsMotionController;
  67528. }(BABYLON.WebVRController));
  67529. BABYLON.WindowsMotionController = WindowsMotionController;
  67530. })(BABYLON || (BABYLON = {}));
  67531. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67532. "use strict";
  67533. var BABYLON;
  67534. (function (BABYLON) {
  67535. var GearVRController = /** @class */ (function (_super) {
  67536. __extends(GearVRController, _super);
  67537. function GearVRController(vrGamepad) {
  67538. var _this = _super.call(this, vrGamepad) || this;
  67539. _this._buttonIndexToObservableNameMap = [
  67540. 'onTrackpadChangedObservable',
  67541. 'onTriggerStateChangedObservable' // Trigger
  67542. ];
  67543. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67544. return _this;
  67545. }
  67546. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67547. var _this = this;
  67548. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67549. _this._defaultModel = newMeshes[1];
  67550. _this.attachToMesh(_this._defaultModel);
  67551. if (meshLoaded) {
  67552. meshLoaded(_this._defaultModel);
  67553. }
  67554. });
  67555. };
  67556. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67557. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67558. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67559. // Only emit events for buttons that we know how to map from index to observable
  67560. var observable = this[observableName];
  67561. if (observable) {
  67562. observable.notifyObservers(state);
  67563. }
  67564. }
  67565. };
  67566. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67567. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67568. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67569. return GearVRController;
  67570. }(BABYLON.WebVRController));
  67571. BABYLON.GearVRController = GearVRController;
  67572. })(BABYLON || (BABYLON = {}));
  67573. //# sourceMappingURL=babylon.gearVRController.js.map
  67574. "use strict";
  67575. var BABYLON;
  67576. (function (BABYLON) {
  67577. /**
  67578. * Google Daydream controller
  67579. */
  67580. var DaydreamController = /** @class */ (function (_super) {
  67581. __extends(DaydreamController, _super);
  67582. function DaydreamController(vrGamepad) {
  67583. var _this = _super.call(this, vrGamepad) || this;
  67584. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67585. return _this;
  67586. }
  67587. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67588. var _this = this;
  67589. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67590. _this._defaultModel = newMeshes[1];
  67591. _this.attachToMesh(_this._defaultModel);
  67592. if (meshLoaded) {
  67593. meshLoaded(_this._defaultModel);
  67594. }
  67595. });
  67596. };
  67597. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67598. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67599. if (buttonIdx === 0) {
  67600. var observable = this.onTriggerStateChangedObservable;
  67601. if (observable) {
  67602. observable.notifyObservers(state);
  67603. }
  67604. }
  67605. else {
  67606. // If the app or home buttons are ever made available
  67607. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67608. }
  67609. };
  67610. /**
  67611. * Base Url for the controller model.
  67612. */
  67613. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67614. /**
  67615. * File name for the controller model.
  67616. */
  67617. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67618. /**
  67619. * Gamepad Id prefix used to identify Daydream Controller.
  67620. */
  67621. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67622. return DaydreamController;
  67623. }(BABYLON.WebVRController));
  67624. BABYLON.DaydreamController = DaydreamController;
  67625. })(BABYLON || (BABYLON = {}));
  67626. //# sourceMappingURL=babylon.daydreamController.js.map
  67627. "use strict";
  67628. var BABYLON;
  67629. (function (BABYLON) {
  67630. var FollowCamera = /** @class */ (function (_super) {
  67631. __extends(FollowCamera, _super);
  67632. function FollowCamera(name, position, scene, lockedTarget) {
  67633. if (lockedTarget === void 0) { lockedTarget = null; }
  67634. var _this = _super.call(this, name, position, scene) || this;
  67635. _this.radius = 12;
  67636. _this.rotationOffset = 0;
  67637. _this.heightOffset = 4;
  67638. _this.cameraAcceleration = 0.05;
  67639. _this.maxCameraSpeed = 20;
  67640. _this.lockedTarget = lockedTarget;
  67641. return _this;
  67642. }
  67643. FollowCamera.prototype.getRadians = function (degrees) {
  67644. return degrees * Math.PI / 180;
  67645. };
  67646. FollowCamera.prototype.follow = function (cameraTarget) {
  67647. if (!cameraTarget)
  67648. return;
  67649. var yRotation;
  67650. if (cameraTarget.rotationQuaternion) {
  67651. var rotMatrix = new BABYLON.Matrix();
  67652. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67653. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67654. }
  67655. else {
  67656. yRotation = cameraTarget.rotation.y;
  67657. }
  67658. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67659. var targetPosition = cameraTarget.getAbsolutePosition();
  67660. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67661. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67662. var dx = targetX - this.position.x;
  67663. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67664. var dz = (targetZ) - this.position.z;
  67665. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67666. var vy = dy * this.cameraAcceleration;
  67667. var vz = dz * this.cameraAcceleration * 2;
  67668. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67669. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67670. }
  67671. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67672. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67673. }
  67674. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67675. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67676. }
  67677. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67678. this.setTarget(targetPosition);
  67679. };
  67680. FollowCamera.prototype._checkInputs = function () {
  67681. _super.prototype._checkInputs.call(this);
  67682. if (this.lockedTarget) {
  67683. this.follow(this.lockedTarget);
  67684. }
  67685. };
  67686. FollowCamera.prototype.getClassName = function () {
  67687. return "FollowCamera";
  67688. };
  67689. __decorate([
  67690. BABYLON.serialize()
  67691. ], FollowCamera.prototype, "radius", void 0);
  67692. __decorate([
  67693. BABYLON.serialize()
  67694. ], FollowCamera.prototype, "rotationOffset", void 0);
  67695. __decorate([
  67696. BABYLON.serialize()
  67697. ], FollowCamera.prototype, "heightOffset", void 0);
  67698. __decorate([
  67699. BABYLON.serialize()
  67700. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67701. __decorate([
  67702. BABYLON.serialize()
  67703. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67704. __decorate([
  67705. BABYLON.serializeAsMeshReference("lockedTargetId")
  67706. ], FollowCamera.prototype, "lockedTarget", void 0);
  67707. return FollowCamera;
  67708. }(BABYLON.TargetCamera));
  67709. BABYLON.FollowCamera = FollowCamera;
  67710. var ArcFollowCamera = /** @class */ (function (_super) {
  67711. __extends(ArcFollowCamera, _super);
  67712. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67713. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67714. _this.alpha = alpha;
  67715. _this.beta = beta;
  67716. _this.radius = radius;
  67717. _this.target = target;
  67718. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67719. _this.follow();
  67720. return _this;
  67721. }
  67722. ArcFollowCamera.prototype.follow = function () {
  67723. if (!this.target) {
  67724. return;
  67725. }
  67726. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67727. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67728. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67729. var targetPosition = this.target.getAbsolutePosition();
  67730. this.position = targetPosition.add(this._cartesianCoordinates);
  67731. this.setTarget(targetPosition);
  67732. };
  67733. ArcFollowCamera.prototype._checkInputs = function () {
  67734. _super.prototype._checkInputs.call(this);
  67735. this.follow();
  67736. };
  67737. ArcFollowCamera.prototype.getClassName = function () {
  67738. return "ArcFollowCamera";
  67739. };
  67740. return ArcFollowCamera;
  67741. }(BABYLON.TargetCamera));
  67742. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67743. })(BABYLON || (BABYLON = {}));
  67744. //# sourceMappingURL=babylon.followCamera.js.map
  67745. "use strict";
  67746. var BABYLON;
  67747. (function (BABYLON) {
  67748. // We're mainly based on the logic defined into the FreeCamera code
  67749. var UniversalCamera = /** @class */ (function (_super) {
  67750. __extends(UniversalCamera, _super);
  67751. //-- end properties for backward compatibility for inputs
  67752. function UniversalCamera(name, position, scene) {
  67753. var _this = _super.call(this, name, position, scene) || this;
  67754. _this.inputs.addGamepad();
  67755. return _this;
  67756. }
  67757. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67758. //-- Begin properties for backward compatibility for inputs
  67759. get: function () {
  67760. var gamepad = this.inputs.attached["gamepad"];
  67761. if (gamepad)
  67762. return gamepad.gamepadAngularSensibility;
  67763. return 0;
  67764. },
  67765. set: function (value) {
  67766. var gamepad = this.inputs.attached["gamepad"];
  67767. if (gamepad)
  67768. gamepad.gamepadAngularSensibility = value;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67774. get: function () {
  67775. var gamepad = this.inputs.attached["gamepad"];
  67776. if (gamepad)
  67777. return gamepad.gamepadMoveSensibility;
  67778. return 0;
  67779. },
  67780. set: function (value) {
  67781. var gamepad = this.inputs.attached["gamepad"];
  67782. if (gamepad)
  67783. gamepad.gamepadMoveSensibility = value;
  67784. },
  67785. enumerable: true,
  67786. configurable: true
  67787. });
  67788. UniversalCamera.prototype.getClassName = function () {
  67789. return "UniversalCamera";
  67790. };
  67791. return UniversalCamera;
  67792. }(BABYLON.TouchCamera));
  67793. BABYLON.UniversalCamera = UniversalCamera;
  67794. })(BABYLON || (BABYLON = {}));
  67795. //# sourceMappingURL=babylon.universalCamera.js.map
  67796. "use strict";
  67797. var BABYLON;
  67798. (function (BABYLON) {
  67799. // We're mainly based on the logic defined into the FreeCamera code
  67800. var GamepadCamera = /** @class */ (function (_super) {
  67801. __extends(GamepadCamera, _super);
  67802. //-- end properties for backward compatibility for inputs
  67803. function GamepadCamera(name, position, scene) {
  67804. return _super.call(this, name, position, scene) || this;
  67805. }
  67806. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67807. //-- Begin properties for backward compatibility for inputs
  67808. get: function () {
  67809. var gamepad = this.inputs.attached["gamepad"];
  67810. if (gamepad)
  67811. return gamepad.gamepadAngularSensibility;
  67812. return 0;
  67813. },
  67814. set: function (value) {
  67815. var gamepad = this.inputs.attached["gamepad"];
  67816. if (gamepad)
  67817. gamepad.gamepadAngularSensibility = value;
  67818. },
  67819. enumerable: true,
  67820. configurable: true
  67821. });
  67822. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67823. get: function () {
  67824. var gamepad = this.inputs.attached["gamepad"];
  67825. if (gamepad)
  67826. return gamepad.gamepadMoveSensibility;
  67827. return 0;
  67828. },
  67829. set: function (value) {
  67830. var gamepad = this.inputs.attached["gamepad"];
  67831. if (gamepad)
  67832. gamepad.gamepadMoveSensibility = value;
  67833. },
  67834. enumerable: true,
  67835. configurable: true
  67836. });
  67837. GamepadCamera.prototype.getClassName = function () {
  67838. return "GamepadCamera";
  67839. };
  67840. return GamepadCamera;
  67841. }(BABYLON.UniversalCamera));
  67842. BABYLON.GamepadCamera = GamepadCamera;
  67843. })(BABYLON || (BABYLON = {}));
  67844. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67845. "use strict";
  67846. var BABYLON;
  67847. (function (BABYLON) {
  67848. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67849. function PostProcessRenderPipelineManager() {
  67850. this._renderPipelines = {};
  67851. }
  67852. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67853. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67854. };
  67855. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67856. if (unique === void 0) { unique = false; }
  67857. var renderPipeline = this._renderPipelines[renderPipelineName];
  67858. if (!renderPipeline) {
  67859. return;
  67860. }
  67861. renderPipeline._attachCameras(cameras, unique);
  67862. };
  67863. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67864. var renderPipeline = this._renderPipelines[renderPipelineName];
  67865. if (!renderPipeline) {
  67866. return;
  67867. }
  67868. renderPipeline._detachCameras(cameras);
  67869. };
  67870. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67871. var renderPipeline = this._renderPipelines[renderPipelineName];
  67872. if (!renderPipeline) {
  67873. return;
  67874. }
  67875. renderPipeline._enableEffect(renderEffectName, cameras);
  67876. };
  67877. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67878. var renderPipeline = this._renderPipelines[renderPipelineName];
  67879. if (!renderPipeline) {
  67880. return;
  67881. }
  67882. renderPipeline._disableEffect(renderEffectName, cameras);
  67883. };
  67884. PostProcessRenderPipelineManager.prototype.update = function () {
  67885. for (var renderPipelineName in this._renderPipelines) {
  67886. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67887. var pipeline = this._renderPipelines[renderPipelineName];
  67888. if (!pipeline.isSupported) {
  67889. pipeline.dispose();
  67890. delete this._renderPipelines[renderPipelineName];
  67891. }
  67892. else {
  67893. pipeline._update();
  67894. }
  67895. }
  67896. }
  67897. };
  67898. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67899. for (var renderPipelineName in this._renderPipelines) {
  67900. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67901. var pipeline = this._renderPipelines[renderPipelineName];
  67902. pipeline._rebuild();
  67903. }
  67904. }
  67905. };
  67906. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67907. for (var renderPipelineName in this._renderPipelines) {
  67908. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67909. var pipeline = this._renderPipelines[renderPipelineName];
  67910. pipeline.dispose();
  67911. }
  67912. }
  67913. };
  67914. return PostProcessRenderPipelineManager;
  67915. }());
  67916. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67917. })(BABYLON || (BABYLON = {}));
  67918. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67919. "use strict";
  67920. var BABYLON;
  67921. (function (BABYLON) {
  67922. /**
  67923. * This represents a set of one or more post processes in Babylon.
  67924. * A post process can be used to apply a shader to a texture after it is rendered.
  67925. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67926. */
  67927. var PostProcessRenderEffect = /** @class */ (function () {
  67928. /**
  67929. * Instantiates a post process render effect.
  67930. * A post process can be used to apply a shader to a texture after it is rendered.
  67931. * @param engine The engine the effect is tied to
  67932. * @param name The name of the effect
  67933. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67934. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67935. */
  67936. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67937. this._name = name;
  67938. this._singleInstance = singleInstance || true;
  67939. this._getPostProcesses = getPostProcesses;
  67940. this._cameras = {};
  67941. this._indicesForCamera = {};
  67942. this._postProcesses = {};
  67943. }
  67944. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67945. /**
  67946. * Checks if all the post processes in the effect are supported.
  67947. */
  67948. get: function () {
  67949. for (var index in this._postProcesses) {
  67950. for (var ppIndex in this._postProcesses[index]) {
  67951. if (!this._postProcesses[index][ppIndex].isSupported) {
  67952. return false;
  67953. }
  67954. }
  67955. }
  67956. return true;
  67957. },
  67958. enumerable: true,
  67959. configurable: true
  67960. });
  67961. /**
  67962. * Updates the current state of the effect
  67963. */
  67964. PostProcessRenderEffect.prototype._update = function () {
  67965. };
  67966. /**
  67967. * Attaches the effect on cameras
  67968. * @param cameras The camera to attach to.
  67969. */
  67970. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67971. var _this = this;
  67972. var cameraKey;
  67973. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67974. if (!cams) {
  67975. return;
  67976. }
  67977. for (var i = 0; i < cams.length; i++) {
  67978. var camera = cams[i];
  67979. var cameraName = camera.name;
  67980. if (this._singleInstance) {
  67981. cameraKey = 0;
  67982. }
  67983. else {
  67984. cameraKey = cameraName;
  67985. }
  67986. if (!this._postProcesses[cameraKey]) {
  67987. var postProcess = this._getPostProcesses();
  67988. if (postProcess) {
  67989. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67990. }
  67991. }
  67992. if (!this._indicesForCamera[cameraName]) {
  67993. this._indicesForCamera[cameraName] = [];
  67994. }
  67995. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67996. var index = camera.attachPostProcess(postProcess);
  67997. _this._indicesForCamera[cameraName].push(index);
  67998. });
  67999. if (!this._cameras[cameraName]) {
  68000. this._cameras[cameraName] = camera;
  68001. }
  68002. }
  68003. };
  68004. /**
  68005. * Detatches the effect on cameras
  68006. * @param cameras The camera to detatch from.
  68007. */
  68008. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  68009. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68010. if (!cams) {
  68011. return;
  68012. }
  68013. for (var i = 0; i < cams.length; i++) {
  68014. var camera = cams[i];
  68015. var cameraName = camera.name;
  68016. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68017. camera.detachPostProcess(postProcess);
  68018. });
  68019. if (this._cameras[cameraName]) {
  68020. //this._indicesForCamera.splice(index, 1);
  68021. this._cameras[cameraName] = null;
  68022. }
  68023. }
  68024. };
  68025. /**
  68026. * Enables the effect on given cameras
  68027. * @param cameras The camera to enable.
  68028. */
  68029. PostProcessRenderEffect.prototype._enable = function (cameras) {
  68030. var _this = this;
  68031. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68032. if (!cams) {
  68033. return;
  68034. }
  68035. for (var i = 0; i < cams.length; i++) {
  68036. var camera = cams[i];
  68037. var cameraName = camera.name;
  68038. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  68039. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  68040. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68041. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  68042. });
  68043. }
  68044. }
  68045. }
  68046. };
  68047. /**
  68048. * Disables the effect on the given cameras
  68049. * @param cameras The camera to disable.
  68050. */
  68051. PostProcessRenderEffect.prototype._disable = function (cameras) {
  68052. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68053. if (!cams) {
  68054. return;
  68055. }
  68056. for (var i = 0; i < cams.length; i++) {
  68057. var camera = cams[i];
  68058. var cameraName = camera.name;
  68059. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68060. camera.detachPostProcess(postProcess);
  68061. });
  68062. }
  68063. };
  68064. /**
  68065. * Gets a list of the post processes contained in the effect.
  68066. * @param camera The camera to get the post processes on.
  68067. * @returns The list of the post processes in the effect.
  68068. */
  68069. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68070. if (this._singleInstance) {
  68071. return this._postProcesses[0];
  68072. }
  68073. else {
  68074. if (!camera) {
  68075. return null;
  68076. }
  68077. return this._postProcesses[camera.name];
  68078. }
  68079. };
  68080. return PostProcessRenderEffect;
  68081. }());
  68082. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68083. })(BABYLON || (BABYLON = {}));
  68084. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68085. "use strict";
  68086. var BABYLON;
  68087. (function (BABYLON) {
  68088. var PostProcessRenderPipeline = /** @class */ (function () {
  68089. function PostProcessRenderPipeline(engine, name) {
  68090. this.engine = engine;
  68091. this._name = name;
  68092. this._renderEffects = {};
  68093. this._renderEffectsForIsolatedPass = new Array();
  68094. this._cameras = [];
  68095. }
  68096. PostProcessRenderPipeline.prototype.getClassName = function () {
  68097. return "PostProcessRenderPipeline";
  68098. };
  68099. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68100. get: function () {
  68101. for (var renderEffectName in this._renderEffects) {
  68102. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68103. if (!this._renderEffects[renderEffectName].isSupported) {
  68104. return false;
  68105. }
  68106. }
  68107. }
  68108. return true;
  68109. },
  68110. enumerable: true,
  68111. configurable: true
  68112. });
  68113. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68114. this._renderEffects[renderEffect._name] = renderEffect;
  68115. };
  68116. // private
  68117. PostProcessRenderPipeline.prototype._rebuild = function () {
  68118. };
  68119. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68120. var renderEffects = this._renderEffects[renderEffectName];
  68121. if (!renderEffects) {
  68122. return;
  68123. }
  68124. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68125. };
  68126. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68127. var renderEffects = this._renderEffects[renderEffectName];
  68128. if (!renderEffects) {
  68129. return;
  68130. }
  68131. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68132. };
  68133. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68134. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68135. if (!cams) {
  68136. return;
  68137. }
  68138. var indicesToDelete = [];
  68139. var i;
  68140. for (i = 0; i < cams.length; i++) {
  68141. var camera = cams[i];
  68142. var cameraName = camera.name;
  68143. if (this._cameras.indexOf(camera) === -1) {
  68144. this._cameras[cameraName] = camera;
  68145. }
  68146. else if (unique) {
  68147. indicesToDelete.push(i);
  68148. }
  68149. }
  68150. for (i = 0; i < indicesToDelete.length; i++) {
  68151. cameras.splice(indicesToDelete[i], 1);
  68152. }
  68153. for (var renderEffectName in this._renderEffects) {
  68154. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68155. this._renderEffects[renderEffectName]._attachCameras(cams);
  68156. }
  68157. }
  68158. };
  68159. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68160. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68161. if (!cams) {
  68162. return;
  68163. }
  68164. for (var renderEffectName in this._renderEffects) {
  68165. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68166. this._renderEffects[renderEffectName]._detachCameras(cams);
  68167. }
  68168. }
  68169. for (var i = 0; i < cams.length; i++) {
  68170. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68171. }
  68172. };
  68173. PostProcessRenderPipeline.prototype._update = function () {
  68174. for (var renderEffectName in this._renderEffects) {
  68175. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68176. this._renderEffects[renderEffectName]._update();
  68177. }
  68178. }
  68179. for (var i = 0; i < this._cameras.length; i++) {
  68180. var cameraName = this._cameras[i].name;
  68181. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68182. this._renderEffectsForIsolatedPass[cameraName]._update();
  68183. }
  68184. }
  68185. };
  68186. PostProcessRenderPipeline.prototype._reset = function () {
  68187. this._renderEffects = {};
  68188. this._renderEffectsForIsolatedPass = new Array();
  68189. };
  68190. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  68191. // 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)
  68192. var effectKeys = Object.keys(this._renderEffects);
  68193. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68194. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68195. if (postProcesses) {
  68196. postProcesses[0].samples = sampleCount;
  68197. return true;
  68198. }
  68199. }
  68200. return false;
  68201. };
  68202. PostProcessRenderPipeline.prototype.dispose = function () {
  68203. // Must be implemented by children
  68204. };
  68205. __decorate([
  68206. BABYLON.serialize()
  68207. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68208. return PostProcessRenderPipeline;
  68209. }());
  68210. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68211. })(BABYLON || (BABYLON = {}));
  68212. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68213. "use strict";
  68214. var BABYLON;
  68215. (function (BABYLON) {
  68216. /**
  68217. * This represents a depth renderer in Babylon.
  68218. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68219. */
  68220. var DepthRenderer = /** @class */ (function () {
  68221. /**
  68222. * Instantiates a depth renderer
  68223. * @param scene The scene the renderer belongs to
  68224. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68225. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68226. */
  68227. function DepthRenderer(scene, type, camera) {
  68228. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68229. if (camera === void 0) { camera = null; }
  68230. var _this = this;
  68231. this._scene = scene;
  68232. this._camera = camera;
  68233. var engine = scene.getEngine();
  68234. // Render target
  68235. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68236. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68237. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68238. this._depthMap.refreshRate = 1;
  68239. this._depthMap.renderParticles = false;
  68240. this._depthMap.renderList = null;
  68241. // Camera to get depth map from to support multiple concurrent cameras
  68242. this._depthMap.activeCamera = this._camera;
  68243. this._depthMap.ignoreCameraViewport = true;
  68244. this._depthMap.useCameraPostProcesses = false;
  68245. // set default depth value to 1.0 (far away)
  68246. this._depthMap.onClearObservable.add(function (engine) {
  68247. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68248. });
  68249. // Custom render function
  68250. var renderSubMesh = function (subMesh) {
  68251. var mesh = subMesh.getRenderingMesh();
  68252. var scene = _this._scene;
  68253. var engine = scene.getEngine();
  68254. var material = subMesh.getMaterial();
  68255. if (!material) {
  68256. return;
  68257. }
  68258. // Culling and reverse (right handed system)
  68259. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68260. // Managing instances
  68261. var batch = mesh._getInstancesRenderList(subMesh._id);
  68262. if (batch.mustReturn) {
  68263. return;
  68264. }
  68265. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68266. var camera = _this._camera || scene.activeCamera;
  68267. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68268. engine.enableEffect(_this._effect);
  68269. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68270. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68271. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68272. // Alpha test
  68273. if (material && material.needAlphaTesting()) {
  68274. var alphaTexture = material.getAlphaTestTexture();
  68275. if (alphaTexture) {
  68276. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68277. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68278. }
  68279. }
  68280. // Bones
  68281. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68282. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68283. }
  68284. // Draw
  68285. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68286. }
  68287. };
  68288. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68289. var index;
  68290. if (depthOnlySubMeshes.length) {
  68291. engine.setColorWrite(false);
  68292. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68293. renderSubMesh(depthOnlySubMeshes.data[index]);
  68294. }
  68295. engine.setColorWrite(true);
  68296. }
  68297. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68298. renderSubMesh(opaqueSubMeshes.data[index]);
  68299. }
  68300. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68301. renderSubMesh(alphaTestSubMeshes.data[index]);
  68302. }
  68303. };
  68304. }
  68305. /**
  68306. * Creates the depth rendering effect and checks if the effect is ready.
  68307. * @param subMesh The submesh to be used to render the depth map of
  68308. * @param useInstances If multiple world instances should be used
  68309. * @returns if the depth renderer is ready to render the depth map
  68310. */
  68311. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68312. var material = subMesh.getMaterial();
  68313. if (material.disableDepthWrite) {
  68314. return false;
  68315. }
  68316. var defines = [];
  68317. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68318. var mesh = subMesh.getMesh();
  68319. // Alpha test
  68320. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68321. defines.push("#define ALPHATEST");
  68322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68323. attribs.push(BABYLON.VertexBuffer.UVKind);
  68324. defines.push("#define UV1");
  68325. }
  68326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68327. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68328. defines.push("#define UV2");
  68329. }
  68330. }
  68331. // Bones
  68332. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68333. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68334. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68335. if (mesh.numBoneInfluencers > 4) {
  68336. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68337. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68338. }
  68339. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68340. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68341. }
  68342. else {
  68343. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68344. }
  68345. // Instances
  68346. if (useInstances) {
  68347. defines.push("#define INSTANCES");
  68348. attribs.push("world0");
  68349. attribs.push("world1");
  68350. attribs.push("world2");
  68351. attribs.push("world3");
  68352. }
  68353. // Get correct effect
  68354. var join = defines.join("\n");
  68355. if (this._cachedDefines !== join) {
  68356. this._cachedDefines = join;
  68357. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68358. }
  68359. return this._effect.isReady();
  68360. };
  68361. /**
  68362. * Gets the texture which the depth map will be written to.
  68363. * @returns The depth map texture
  68364. */
  68365. DepthRenderer.prototype.getDepthMap = function () {
  68366. return this._depthMap;
  68367. };
  68368. /**
  68369. * Disposes of the depth renderer.
  68370. */
  68371. DepthRenderer.prototype.dispose = function () {
  68372. this._depthMap.dispose();
  68373. };
  68374. return DepthRenderer;
  68375. }());
  68376. BABYLON.DepthRenderer = DepthRenderer;
  68377. })(BABYLON || (BABYLON = {}));
  68378. //# sourceMappingURL=babylon.depthRenderer.js.map
  68379. "use strict";
  68380. var BABYLON;
  68381. (function (BABYLON) {
  68382. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68383. __extends(SSAORenderingPipeline, _super);
  68384. /**
  68385. * @constructor
  68386. * @param {string} name - The rendering pipeline name
  68387. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68388. * @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 }
  68389. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68390. */
  68391. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68392. var _this = _super.call(this, scene.getEngine(), name) || this;
  68393. // Members
  68394. /**
  68395. * The PassPostProcess id in the pipeline that contains the original scene color
  68396. * @type {string}
  68397. */
  68398. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68399. /**
  68400. * The SSAO PostProcess id in the pipeline
  68401. * @type {string}
  68402. */
  68403. _this.SSAORenderEffect = "SSAORenderEffect";
  68404. /**
  68405. * The horizontal blur PostProcess id in the pipeline
  68406. * @type {string}
  68407. */
  68408. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68409. /**
  68410. * The vertical blur PostProcess id in the pipeline
  68411. * @type {string}
  68412. */
  68413. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68414. /**
  68415. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68416. * @type {string}
  68417. */
  68418. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68419. /**
  68420. * The output strength of the SSAO post-process. Default value is 1.0.
  68421. * @type {number}
  68422. */
  68423. _this.totalStrength = 1.0;
  68424. /**
  68425. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68426. * @type {number}
  68427. */
  68428. _this.radius = 0.0001;
  68429. /**
  68430. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68431. * Must not be equal to fallOff and superior to fallOff.
  68432. * Default value is 0.975
  68433. * @type {number}
  68434. */
  68435. _this.area = 0.0075;
  68436. /**
  68437. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68438. * Must not be equal to area and inferior to area.
  68439. * Default value is 0.0
  68440. * @type {number}
  68441. */
  68442. _this.fallOff = 0.000001;
  68443. /**
  68444. * The base color of the SSAO post-process
  68445. * The final result is "base + ssao" between [0, 1]
  68446. * @type {number}
  68447. */
  68448. _this.base = 0.5;
  68449. _this._firstUpdate = true;
  68450. _this._scene = scene;
  68451. // Set up assets
  68452. _this._createRandomTexture();
  68453. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68454. var ssaoRatio = ratio.ssaoRatio || ratio;
  68455. var combineRatio = ratio.combineRatio || ratio;
  68456. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68457. _this._createSSAOPostProcess(ssaoRatio);
  68458. _this._createBlurPostProcess(ssaoRatio);
  68459. _this._createSSAOCombinePostProcess(combineRatio);
  68460. // Set up pipeline
  68461. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68462. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68463. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68464. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68465. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68466. // Finish
  68467. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68468. if (cameras)
  68469. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68470. return _this;
  68471. }
  68472. // Public Methods
  68473. /**
  68474. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68475. */
  68476. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68477. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68478. for (var i = 0; i < this._scene.cameras.length; i++) {
  68479. var camera = this._scene.cameras[i];
  68480. this._originalColorPostProcess.dispose(camera);
  68481. this._ssaoPostProcess.dispose(camera);
  68482. this._blurHPostProcess.dispose(camera);
  68483. this._blurVPostProcess.dispose(camera);
  68484. this._ssaoCombinePostProcess.dispose(camera);
  68485. }
  68486. this._randomTexture.dispose();
  68487. if (disableDepthRender)
  68488. this._scene.disableDepthRenderer();
  68489. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68490. _super.prototype.dispose.call(this);
  68491. };
  68492. // Private Methods
  68493. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68494. var _this = this;
  68495. var size = 16;
  68496. 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);
  68497. 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);
  68498. this._blurHPostProcess.onActivateObservable.add(function () {
  68499. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68500. _this._blurHPostProcess.kernel = size * dw;
  68501. });
  68502. this._blurVPostProcess.onActivateObservable.add(function () {
  68503. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68504. _this._blurVPostProcess.kernel = size * dw;
  68505. });
  68506. };
  68507. SSAORenderingPipeline.prototype._rebuild = function () {
  68508. this._firstUpdate = true;
  68509. _super.prototype._rebuild.call(this);
  68510. };
  68511. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68512. var _this = this;
  68513. var numSamples = 16;
  68514. var sampleSphere = [
  68515. 0.5381, 0.1856, -0.4319,
  68516. 0.1379, 0.2486, 0.4430,
  68517. 0.3371, 0.5679, -0.0057,
  68518. -0.6999, -0.0451, -0.0019,
  68519. 0.0689, -0.1598, -0.8547,
  68520. 0.0560, 0.0069, -0.1843,
  68521. -0.0146, 0.1402, 0.0762,
  68522. 0.0100, -0.1924, -0.0344,
  68523. -0.3577, -0.5301, -0.4358,
  68524. -0.3169, 0.1063, 0.0158,
  68525. 0.0103, -0.5869, 0.0046,
  68526. -0.0897, -0.4940, 0.3287,
  68527. 0.7119, -0.0154, -0.0918,
  68528. -0.0533, 0.0596, -0.5411,
  68529. 0.0352, -0.0631, 0.5460,
  68530. -0.4776, 0.2847, -0.0271
  68531. ];
  68532. var samplesFactor = 1.0 / numSamples;
  68533. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68534. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68535. "area", "fallOff", "base", "range", "viewport"
  68536. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68537. this._ssaoPostProcess.onApply = function (effect) {
  68538. if (_this._firstUpdate) {
  68539. effect.setArray3("sampleSphere", sampleSphere);
  68540. effect.setFloat("samplesFactor", samplesFactor);
  68541. effect.setFloat("randTextureTiles", 4.0);
  68542. }
  68543. effect.setFloat("totalStrength", _this.totalStrength);
  68544. effect.setFloat("radius", _this.radius);
  68545. effect.setFloat("area", _this.area);
  68546. effect.setFloat("fallOff", _this.fallOff);
  68547. effect.setFloat("base", _this.base);
  68548. effect.setTexture("textureSampler", _this._depthTexture);
  68549. effect.setTexture("randomSampler", _this._randomTexture);
  68550. };
  68551. };
  68552. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68553. var _this = this;
  68554. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68555. this._ssaoCombinePostProcess.onApply = function (effect) {
  68556. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68557. };
  68558. };
  68559. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68560. var size = 512;
  68561. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68562. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68563. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68564. var context = this._randomTexture.getContext();
  68565. var rand = function (min, max) {
  68566. return Math.random() * (max - min) + min;
  68567. };
  68568. var randVector = BABYLON.Vector3.Zero();
  68569. for (var x = 0; x < size; x++) {
  68570. for (var y = 0; y < size; y++) {
  68571. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68572. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68573. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68574. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68575. context.fillRect(x, y, 1, 1);
  68576. }
  68577. }
  68578. this._randomTexture.update(false);
  68579. };
  68580. __decorate([
  68581. BABYLON.serialize()
  68582. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68583. __decorate([
  68584. BABYLON.serialize()
  68585. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68586. __decorate([
  68587. BABYLON.serialize()
  68588. ], SSAORenderingPipeline.prototype, "area", void 0);
  68589. __decorate([
  68590. BABYLON.serialize()
  68591. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68592. __decorate([
  68593. BABYLON.serialize()
  68594. ], SSAORenderingPipeline.prototype, "base", void 0);
  68595. return SSAORenderingPipeline;
  68596. }(BABYLON.PostProcessRenderPipeline));
  68597. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68598. })(BABYLON || (BABYLON = {}));
  68599. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68600. "use strict";
  68601. var BABYLON;
  68602. (function (BABYLON) {
  68603. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68604. __extends(SSAO2RenderingPipeline, _super);
  68605. /**
  68606. * @constructor
  68607. * @param {string} name - The rendering pipeline name
  68608. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68609. * @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 }
  68610. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68611. */
  68612. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68613. var _this = _super.call(this, scene.getEngine(), name) || this;
  68614. // Members
  68615. /**
  68616. * The PassPostProcess id in the pipeline that contains the original scene color
  68617. * @type {string}
  68618. */
  68619. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68620. /**
  68621. * The SSAO PostProcess id in the pipeline
  68622. * @type {string}
  68623. */
  68624. _this.SSAORenderEffect = "SSAORenderEffect";
  68625. /**
  68626. * The horizontal blur PostProcess id in the pipeline
  68627. * @type {string}
  68628. */
  68629. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68630. /**
  68631. * The vertical blur PostProcess id in the pipeline
  68632. * @type {string}
  68633. */
  68634. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68635. /**
  68636. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68637. * @type {string}
  68638. */
  68639. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68640. /**
  68641. * The output strength of the SSAO post-process. Default value is 1.0.
  68642. * @type {number}
  68643. */
  68644. _this.totalStrength = 1.0;
  68645. /**
  68646. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68647. * @type {number}
  68648. */
  68649. _this.maxZ = 100.0;
  68650. /**
  68651. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68652. * @type {number}
  68653. */
  68654. _this.minZAspect = 0.2;
  68655. /**
  68656. * Number of samples used for the SSAO calculations. Default value is 8
  68657. * @type {number}
  68658. */
  68659. _this._samples = 8;
  68660. /**
  68661. * Are we using bilateral blur ?
  68662. * @type {boolean}
  68663. */
  68664. _this._expensiveBlur = true;
  68665. /**
  68666. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68667. * @type {number}
  68668. */
  68669. _this.radius = 2.0;
  68670. /**
  68671. * The base color of the SSAO post-process
  68672. * The final result is "base + ssao" between [0, 1]
  68673. * @type {number}
  68674. */
  68675. _this.base = 0.1;
  68676. _this._firstUpdate = true;
  68677. _this._scene = scene;
  68678. if (!_this.isSupported) {
  68679. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68680. return _this;
  68681. }
  68682. var ssaoRatio = ratio.ssaoRatio || ratio;
  68683. var blurRatio = ratio.blurRatio || ratio;
  68684. // Set up assets
  68685. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68686. _this._createRandomTexture();
  68687. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68688. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68689. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68690. _this._createSSAOPostProcess(1.0);
  68691. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68692. _this._createSSAOCombinePostProcess(blurRatio);
  68693. // Set up pipeline
  68694. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68695. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68696. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68697. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68698. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68699. // Finish
  68700. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68701. if (cameras)
  68702. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68703. return _this;
  68704. }
  68705. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68706. get: function () {
  68707. return this._samples;
  68708. },
  68709. set: function (n) {
  68710. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68711. this._samples = n;
  68712. this._sampleSphere = this._generateHemisphere();
  68713. this._firstUpdate = true;
  68714. },
  68715. enumerable: true,
  68716. configurable: true
  68717. });
  68718. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68719. get: function () {
  68720. return this._expensiveBlur;
  68721. },
  68722. set: function (b) {
  68723. 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"]);
  68724. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68725. this._expensiveBlur = b;
  68726. this._firstUpdate = true;
  68727. },
  68728. enumerable: true,
  68729. configurable: true
  68730. });
  68731. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68732. /**
  68733. * Support test.
  68734. * @type {boolean}
  68735. */
  68736. get: function () {
  68737. var engine = BABYLON.Engine.LastCreatedEngine;
  68738. if (!engine) {
  68739. return false;
  68740. }
  68741. return engine.getCaps().drawBuffersExtension;
  68742. },
  68743. enumerable: true,
  68744. configurable: true
  68745. });
  68746. // Public Methods
  68747. /**
  68748. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68749. */
  68750. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68751. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68752. for (var i = 0; i < this._scene.cameras.length; i++) {
  68753. var camera = this._scene.cameras[i];
  68754. this._originalColorPostProcess.dispose(camera);
  68755. this._ssaoPostProcess.dispose(camera);
  68756. this._blurHPostProcess.dispose(camera);
  68757. this._blurVPostProcess.dispose(camera);
  68758. this._ssaoCombinePostProcess.dispose(camera);
  68759. }
  68760. this._randomTexture.dispose();
  68761. if (disableGeometryBufferRenderer)
  68762. this._scene.disableGeometryBufferRenderer();
  68763. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68764. _super.prototype.dispose.call(this);
  68765. };
  68766. // Private Methods
  68767. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68768. var _this = this;
  68769. this._samplerOffsets = [];
  68770. var expensive = this.expensiveBlur;
  68771. for (var i = -8; i < 8; i++) {
  68772. this._samplerOffsets.push(i * 2 + 0.5);
  68773. }
  68774. 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");
  68775. this._blurHPostProcess.onApply = function (effect) {
  68776. if (!_this._scene.activeCamera) {
  68777. return;
  68778. }
  68779. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68780. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68781. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68782. effect.setFloat("radius", _this.radius);
  68783. effect.setTexture("depthSampler", _this._depthTexture);
  68784. if (_this._firstUpdate) {
  68785. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68786. }
  68787. };
  68788. 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");
  68789. this._blurVPostProcess.onApply = function (effect) {
  68790. if (!_this._scene.activeCamera) {
  68791. return;
  68792. }
  68793. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68794. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68795. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68796. effect.setFloat("radius", _this.radius);
  68797. effect.setTexture("depthSampler", _this._depthTexture);
  68798. if (_this._firstUpdate) {
  68799. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68800. _this._firstUpdate = false;
  68801. }
  68802. };
  68803. };
  68804. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68805. this._firstUpdate = true;
  68806. _super.prototype._rebuild.call(this);
  68807. };
  68808. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68809. var numSamples = this.samples;
  68810. var result = [];
  68811. var vector, scale;
  68812. var rand = function (min, max) {
  68813. return Math.random() * (max - min) + min;
  68814. };
  68815. var i = 0;
  68816. while (i < numSamples) {
  68817. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68818. vector.normalize();
  68819. scale = i / numSamples;
  68820. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68821. vector.scaleInPlace(scale);
  68822. result.push(vector.x, vector.y, vector.z);
  68823. i++;
  68824. }
  68825. return result;
  68826. };
  68827. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68828. var _this = this;
  68829. var numSamples = this.samples;
  68830. this._sampleSphere = this._generateHemisphere();
  68831. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68832. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68833. "base", "range", "projection", "near", "far", "texelSize",
  68834. "xViewport", "yViewport", "maxZ", "minZAspect"
  68835. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68836. this._ssaoPostProcess.onApply = function (effect) {
  68837. if (_this._firstUpdate) {
  68838. effect.setArray3("sampleSphere", _this._sampleSphere);
  68839. effect.setFloat("randTextureTiles", 4.0);
  68840. }
  68841. if (!_this._scene.activeCamera) {
  68842. return;
  68843. }
  68844. effect.setFloat("samplesFactor", 1 / _this.samples);
  68845. effect.setFloat("totalStrength", _this.totalStrength);
  68846. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68847. effect.setFloat("radius", _this.radius);
  68848. effect.setFloat("maxZ", _this.maxZ);
  68849. effect.setFloat("minZAspect", _this.minZAspect);
  68850. effect.setFloat("base", _this.base);
  68851. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68852. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68853. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68854. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68855. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68856. effect.setTexture("textureSampler", _this._depthTexture);
  68857. effect.setTexture("normalSampler", _this._normalTexture);
  68858. effect.setTexture("randomSampler", _this._randomTexture);
  68859. };
  68860. };
  68861. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68862. var _this = this;
  68863. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68864. this._ssaoCombinePostProcess.onApply = function (effect) {
  68865. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68866. };
  68867. };
  68868. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68869. var size = 512;
  68870. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68871. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68872. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68873. var context = this._randomTexture.getContext();
  68874. var rand = function (min, max) {
  68875. return Math.random() * (max - min) + min;
  68876. };
  68877. var randVector = BABYLON.Vector3.Zero();
  68878. for (var x = 0; x < size; x++) {
  68879. for (var y = 0; y < size; y++) {
  68880. randVector.x = rand(0.0, 1.0);
  68881. randVector.y = rand(0.0, 1.0);
  68882. randVector.z = 0.0;
  68883. randVector.normalize();
  68884. randVector.scaleInPlace(255);
  68885. randVector.x = Math.floor(randVector.x);
  68886. randVector.y = Math.floor(randVector.y);
  68887. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68888. context.fillRect(x, y, 1, 1);
  68889. }
  68890. }
  68891. this._randomTexture.update(false);
  68892. };
  68893. __decorate([
  68894. BABYLON.serialize()
  68895. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68896. __decorate([
  68897. BABYLON.serialize()
  68898. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68899. __decorate([
  68900. BABYLON.serialize()
  68901. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68902. __decorate([
  68903. BABYLON.serialize("samples")
  68904. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68905. __decorate([
  68906. BABYLON.serialize("expensiveBlur")
  68907. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68908. __decorate([
  68909. BABYLON.serialize()
  68910. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68911. __decorate([
  68912. BABYLON.serialize()
  68913. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68914. return SSAO2RenderingPipeline;
  68915. }(BABYLON.PostProcessRenderPipeline));
  68916. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68917. })(BABYLON || (BABYLON = {}));
  68918. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68919. "use strict";
  68920. // BABYLON.JS Chromatic Aberration GLSL Shader
  68921. // Author: Olivier Guyot
  68922. // Separates very slightly R, G and B colors on the edges of the screen
  68923. // Inspired by Francois Tarlier & Martins Upitis
  68924. var BABYLON;
  68925. (function (BABYLON) {
  68926. var LensRenderingPipeline = /** @class */ (function (_super) {
  68927. __extends(LensRenderingPipeline, _super);
  68928. /**
  68929. * @constructor
  68930. *
  68931. * Effect parameters are as follow:
  68932. * {
  68933. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68934. * edge_blur: number; // from 0 to x (1 for realism)
  68935. * distortion: number; // from 0 to x (1 for realism)
  68936. * grain_amount: number; // from 0 to 1
  68937. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68938. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68939. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68940. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68941. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68942. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68943. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68944. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68945. * }
  68946. * Note: if an effect parameter is unset, effect is disabled
  68947. *
  68948. * @param {string} name - The rendering pipeline name
  68949. * @param {object} parameters - An object containing all parameters (see above)
  68950. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68951. * @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)
  68952. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68953. */
  68954. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68955. if (ratio === void 0) { ratio = 1.0; }
  68956. var _this = _super.call(this, scene.getEngine(), name) || this;
  68957. // Lens effects can be of the following:
  68958. // - chromatic aberration (slight shift of RGB colors)
  68959. // - blur on the edge of the lens
  68960. // - lens distortion
  68961. // - depth-of-field blur & highlights enhancing
  68962. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68963. // - grain effect (noise or custom texture)
  68964. // Two additional texture samplers are needed:
  68965. // - depth map (for depth-of-field)
  68966. // - grain texture
  68967. /**
  68968. * The chromatic aberration PostProcess id in the pipeline
  68969. * @type {string}
  68970. */
  68971. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68972. /**
  68973. * The highlights enhancing PostProcess id in the pipeline
  68974. * @type {string}
  68975. */
  68976. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68977. /**
  68978. * The depth-of-field PostProcess id in the pipeline
  68979. * @type {string}
  68980. */
  68981. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68982. _this._scene = scene;
  68983. // Fetch texture samplers
  68984. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68985. if (parameters.grain_texture) {
  68986. _this._grainTexture = parameters.grain_texture;
  68987. }
  68988. else {
  68989. _this._createGrainTexture();
  68990. }
  68991. // save parameters
  68992. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68993. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68994. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68995. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68996. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68997. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68998. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68999. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  69000. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  69001. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  69002. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  69003. // Create effects
  69004. _this._createChromaticAberrationPostProcess(ratio);
  69005. _this._createHighlightsPostProcess(ratio);
  69006. _this._createDepthOfFieldPostProcess(ratio / 4);
  69007. // Set up pipeline
  69008. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  69009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  69010. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  69011. if (_this._highlightsGain === -1) {
  69012. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  69013. }
  69014. // Finish
  69015. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69016. if (cameras) {
  69017. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69018. }
  69019. return _this;
  69020. }
  69021. // public methods (self explanatory)
  69022. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  69023. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  69024. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  69025. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  69026. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  69027. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  69028. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  69029. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  69030. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  69031. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  69032. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  69033. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  69034. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  69035. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  69036. };
  69037. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  69038. this._highlightsPostProcess.updateEffect();
  69039. };
  69040. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  69041. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  69042. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  69043. this._highlightsGain = amount;
  69044. };
  69045. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  69046. if (this._highlightsGain === -1) {
  69047. this._highlightsGain = 1.0;
  69048. }
  69049. this._highlightsThreshold = amount;
  69050. };
  69051. LensRenderingPipeline.prototype.disableHighlights = function () {
  69052. this._highlightsGain = -1;
  69053. };
  69054. /**
  69055. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69056. */
  69057. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69058. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69059. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69060. this._chromaticAberrationPostProcess = null;
  69061. this._highlightsPostProcess = null;
  69062. this._depthOfFieldPostProcess = null;
  69063. this._grainTexture.dispose();
  69064. if (disableDepthRender)
  69065. this._scene.disableDepthRenderer();
  69066. };
  69067. // colors shifting and distortion
  69068. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69069. var _this = this;
  69070. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69071. [], // samplers
  69072. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69073. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69074. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69077. effect.setFloat('radialIntensity', 1);
  69078. effect.setFloat2('direction', 17, 17);
  69079. effect.setFloat2('centerPosition', 0.5, 0.5);
  69080. };
  69081. };
  69082. // highlights enhancing
  69083. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69084. var _this = this;
  69085. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69086. [], // samplers
  69087. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69088. this._highlightsPostProcess.onApply = function (effect) {
  69089. effect.setFloat('gain', _this._highlightsGain);
  69090. effect.setFloat('threshold', _this._highlightsThreshold);
  69091. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69092. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69093. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69094. };
  69095. };
  69096. // colors shifting and distortion
  69097. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69098. var _this = this;
  69099. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69100. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69101. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69102. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69103. this._depthOfFieldPostProcess.onApply = function (effect) {
  69104. effect.setTexture("depthSampler", _this._depthTexture);
  69105. effect.setTexture("grainSampler", _this._grainTexture);
  69106. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69107. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69108. effect.setFloat('grain_amount', _this._grainAmount);
  69109. effect.setBool('blur_noise', _this._blurNoise);
  69110. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69111. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69112. effect.setFloat('distortion', _this._distortion);
  69113. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69114. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69115. effect.setFloat('aperture', _this._dofAperture);
  69116. effect.setFloat('darken', _this._dofDarken);
  69117. effect.setFloat('edge_blur', _this._edgeBlur);
  69118. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69119. if (_this._scene.activeCamera) {
  69120. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69121. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69122. }
  69123. };
  69124. };
  69125. // creates a black and white random noise texture, 512x512
  69126. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69127. var size = 512;
  69128. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69129. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69130. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69131. var context = this._grainTexture.getContext();
  69132. var rand = function (min, max) {
  69133. return Math.random() * (max - min) + min;
  69134. };
  69135. var value;
  69136. for (var x = 0; x < size; x++) {
  69137. for (var y = 0; y < size; y++) {
  69138. value = Math.floor(rand(0.42, 0.58) * 255);
  69139. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69140. context.fillRect(x, y, 1, 1);
  69141. }
  69142. }
  69143. this._grainTexture.update(false);
  69144. };
  69145. return LensRenderingPipeline;
  69146. }(BABYLON.PostProcessRenderPipeline));
  69147. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69148. })(BABYLON || (BABYLON = {}));
  69149. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69150. "use strict";
  69151. var BABYLON;
  69152. (function (BABYLON) {
  69153. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69154. __extends(StandardRenderingPipeline, _super);
  69155. /**
  69156. * @constructor
  69157. * @param {string} name - The rendering pipeline name
  69158. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69159. * @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)
  69160. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69161. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69162. */
  69163. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69164. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69165. var _this = _super.call(this, scene.getEngine(), name) || this;
  69166. _this.downSampleX4PostProcess = null;
  69167. _this.brightPassPostProcess = null;
  69168. _this.blurHPostProcesses = [];
  69169. _this.blurVPostProcesses = [];
  69170. _this.textureAdderPostProcess = null;
  69171. _this.volumetricLightPostProcess = null;
  69172. _this.volumetricLightSmoothXPostProcess = null;
  69173. _this.volumetricLightSmoothYPostProcess = null;
  69174. _this.volumetricLightMergePostProces = null;
  69175. _this.volumetricLightFinalPostProcess = null;
  69176. _this.luminancePostProcess = null;
  69177. _this.luminanceDownSamplePostProcesses = [];
  69178. _this.hdrPostProcess = null;
  69179. _this.textureAdderFinalPostProcess = null;
  69180. _this.lensFlareFinalPostProcess = null;
  69181. _this.hdrFinalPostProcess = null;
  69182. _this.lensFlarePostProcess = null;
  69183. _this.lensFlareComposePostProcess = null;
  69184. _this.motionBlurPostProcess = null;
  69185. _this.depthOfFieldPostProcess = null;
  69186. // Values
  69187. _this.brightThreshold = 1.0;
  69188. _this.blurWidth = 512.0;
  69189. _this.horizontalBlur = false;
  69190. _this.exposure = 1.0;
  69191. _this.lensTexture = null;
  69192. _this.volumetricLightCoefficient = 0.2;
  69193. _this.volumetricLightPower = 4.0;
  69194. _this.volumetricLightBlurScale = 64.0;
  69195. _this.sourceLight = null;
  69196. _this.hdrMinimumLuminance = 1.0;
  69197. _this.hdrDecreaseRate = 0.5;
  69198. _this.hdrIncreaseRate = 0.5;
  69199. _this.lensColorTexture = null;
  69200. _this.lensFlareStrength = 20.0;
  69201. _this.lensFlareGhostDispersal = 1.4;
  69202. _this.lensFlareHaloWidth = 0.7;
  69203. _this.lensFlareDistortionStrength = 16.0;
  69204. _this.lensStarTexture = null;
  69205. _this.lensFlareDirtTexture = null;
  69206. _this.depthOfFieldDistance = 10.0;
  69207. _this.depthOfFieldBlurWidth = 64.0;
  69208. _this.motionStrength = 1.0;
  69209. // IAnimatable
  69210. _this.animations = [];
  69211. _this._currentDepthOfFieldSource = null;
  69212. _this._hdrCurrentLuminance = 1.0;
  69213. // Getters and setters
  69214. _this._bloomEnabled = true;
  69215. _this._depthOfFieldEnabled = false;
  69216. _this._vlsEnabled = false;
  69217. _this._lensFlareEnabled = false;
  69218. _this._hdrEnabled = false;
  69219. _this._motionBlurEnabled = false;
  69220. _this._motionBlurSamples = 64.0;
  69221. _this._volumetricLightStepsCount = 50.0;
  69222. _this._cameras = cameras || [];
  69223. // Initialize
  69224. _this._scene = scene;
  69225. _this._basePostProcess = originalPostProcess;
  69226. _this._ratio = ratio;
  69227. // Misc
  69228. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69229. // Finish
  69230. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69231. _this._buildPipeline();
  69232. return _this;
  69233. }
  69234. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69235. get: function () {
  69236. return this._bloomEnabled;
  69237. },
  69238. set: function (enabled) {
  69239. if (this._bloomEnabled === enabled) {
  69240. return;
  69241. }
  69242. this._bloomEnabled = enabled;
  69243. this._buildPipeline();
  69244. },
  69245. enumerable: true,
  69246. configurable: true
  69247. });
  69248. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69249. get: function () {
  69250. return this._depthOfFieldEnabled;
  69251. },
  69252. set: function (enabled) {
  69253. if (this._depthOfFieldEnabled === enabled) {
  69254. return;
  69255. }
  69256. this._depthOfFieldEnabled = enabled;
  69257. this._buildPipeline();
  69258. },
  69259. enumerable: true,
  69260. configurable: true
  69261. });
  69262. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69263. get: function () {
  69264. return this._lensFlareEnabled;
  69265. },
  69266. set: function (enabled) {
  69267. if (this._lensFlareEnabled === enabled) {
  69268. return;
  69269. }
  69270. this._lensFlareEnabled = enabled;
  69271. this._buildPipeline();
  69272. },
  69273. enumerable: true,
  69274. configurable: true
  69275. });
  69276. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69277. get: function () {
  69278. return this._hdrEnabled;
  69279. },
  69280. set: function (enabled) {
  69281. if (this._hdrEnabled === enabled) {
  69282. return;
  69283. }
  69284. this._hdrEnabled = enabled;
  69285. this._buildPipeline();
  69286. },
  69287. enumerable: true,
  69288. configurable: true
  69289. });
  69290. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69291. get: function () {
  69292. return this._vlsEnabled;
  69293. },
  69294. set: function (enabled) {
  69295. if (this._vlsEnabled === enabled) {
  69296. return;
  69297. }
  69298. if (enabled) {
  69299. var geometry = this._scene.enableGeometryBufferRenderer();
  69300. if (!geometry) {
  69301. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69302. return;
  69303. }
  69304. }
  69305. this._vlsEnabled = enabled;
  69306. this._buildPipeline();
  69307. },
  69308. enumerable: true,
  69309. configurable: true
  69310. });
  69311. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69312. get: function () {
  69313. return this._motionBlurEnabled;
  69314. },
  69315. set: function (enabled) {
  69316. if (this._motionBlurEnabled === enabled) {
  69317. return;
  69318. }
  69319. this._motionBlurEnabled = enabled;
  69320. this._buildPipeline();
  69321. },
  69322. enumerable: true,
  69323. configurable: true
  69324. });
  69325. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69326. get: function () {
  69327. return this._volumetricLightStepsCount;
  69328. },
  69329. set: function (count) {
  69330. if (this.volumetricLightPostProcess) {
  69331. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69332. }
  69333. this._volumetricLightStepsCount = count;
  69334. },
  69335. enumerable: true,
  69336. configurable: true
  69337. });
  69338. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69339. get: function () {
  69340. return this._motionBlurSamples;
  69341. },
  69342. set: function (samples) {
  69343. if (this.motionBlurPostProcess) {
  69344. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69345. }
  69346. this._motionBlurSamples = samples;
  69347. },
  69348. enumerable: true,
  69349. configurable: true
  69350. });
  69351. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69352. var _this = this;
  69353. var ratio = this._ratio;
  69354. var scene = this._scene;
  69355. this._disposePostProcesses();
  69356. this._reset();
  69357. // Create pass post-process
  69358. if (!this._basePostProcess) {
  69359. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69360. this.originalPostProcess.onApply = function (effect) {
  69361. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69362. };
  69363. }
  69364. else {
  69365. this.originalPostProcess = this._basePostProcess;
  69366. }
  69367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69368. this._currentDepthOfFieldSource = this.originalPostProcess;
  69369. if (this._vlsEnabled) {
  69370. // Create volumetric light
  69371. this._createVolumetricLightPostProcess(scene, ratio);
  69372. // Create volumetric light final post-process
  69373. 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);
  69374. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69375. }
  69376. if (this._bloomEnabled) {
  69377. // Create down sample X4 post-process
  69378. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69379. // Create bright pass post-process
  69380. this._createBrightPassPostProcess(scene, ratio / 2);
  69381. // Create gaussian blur post-processes (down sampling blurs)
  69382. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69383. // Create texture adder post-process
  69384. this._createTextureAdderPostProcess(scene, ratio);
  69385. // Create depth-of-field source post-process
  69386. 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);
  69387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69388. }
  69389. if (this._lensFlareEnabled) {
  69390. // Create lens flare post-process
  69391. this._createLensFlarePostProcess(scene, ratio);
  69392. // Create depth-of-field source post-process post lens-flare and disable it now
  69393. 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);
  69394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69395. }
  69396. if (this._hdrEnabled) {
  69397. // Create luminance
  69398. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69399. // Create HDR
  69400. this._createHdrPostProcess(scene, ratio);
  69401. // Create depth-of-field source post-process post hdr and disable it now
  69402. 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);
  69403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69404. }
  69405. if (this._depthOfFieldEnabled) {
  69406. // Create gaussian blur used by depth-of-field
  69407. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69408. // Create depth-of-field post-process
  69409. this._createDepthOfFieldPostProcess(scene, ratio);
  69410. }
  69411. if (this._motionBlurEnabled) {
  69412. // Create motion blur post-process
  69413. this._createMotionBlurPostProcess(scene, ratio);
  69414. }
  69415. if (this._cameras !== null) {
  69416. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69417. }
  69418. };
  69419. // Down Sample X4 Post-Processs
  69420. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69421. var _this = this;
  69422. var downSampleX4Offsets = new Array(32);
  69423. 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);
  69424. this.downSampleX4PostProcess.onApply = function (effect) {
  69425. var id = 0;
  69426. var width = _this.downSampleX4PostProcess.width;
  69427. var height = _this.downSampleX4PostProcess.height;
  69428. for (var i = -2; i < 2; i++) {
  69429. for (var j = -2; j < 2; j++) {
  69430. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69431. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69432. id += 2;
  69433. }
  69434. }
  69435. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69436. };
  69437. // Add to pipeline
  69438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69439. };
  69440. // Brightpass Post-Process
  69441. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69442. var _this = this;
  69443. var brightOffsets = new Array(8);
  69444. 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);
  69445. this.brightPassPostProcess.onApply = function (effect) {
  69446. var sU = (1.0 / _this.brightPassPostProcess.width);
  69447. var sV = (1.0 / _this.brightPassPostProcess.height);
  69448. brightOffsets[0] = -0.5 * sU;
  69449. brightOffsets[1] = 0.5 * sV;
  69450. brightOffsets[2] = 0.5 * sU;
  69451. brightOffsets[3] = 0.5 * sV;
  69452. brightOffsets[4] = -0.5 * sU;
  69453. brightOffsets[5] = -0.5 * sV;
  69454. brightOffsets[6] = 0.5 * sU;
  69455. brightOffsets[7] = -0.5 * sV;
  69456. effect.setArray2("dsOffsets", brightOffsets);
  69457. effect.setFloat("brightThreshold", _this.brightThreshold);
  69458. };
  69459. // Add to pipeline
  69460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69461. };
  69462. // Create blur H&V post-processes
  69463. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69464. var _this = this;
  69465. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69466. var engine = scene.getEngine();
  69467. 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);
  69468. 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);
  69469. blurX.onActivateObservable.add(function () {
  69470. var dw = blurX.width / engine.getRenderWidth();
  69471. blurX.kernel = _this[blurWidthKey] * dw;
  69472. });
  69473. blurY.onActivateObservable.add(function () {
  69474. var dw = blurY.height / engine.getRenderHeight();
  69475. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69476. });
  69477. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69479. this.blurHPostProcesses.push(blurX);
  69480. this.blurVPostProcesses.push(blurY);
  69481. };
  69482. // Create texture adder post-process
  69483. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69484. var _this = this;
  69485. 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);
  69486. this.textureAdderPostProcess.onApply = function (effect) {
  69487. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69488. effect.setTexture("lensSampler", _this.lensTexture);
  69489. effect.setFloat("exposure", _this.exposure);
  69490. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69491. };
  69492. // Add to pipeline
  69493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69494. };
  69495. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69496. var _this = this;
  69497. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69498. geometryRenderer.enablePosition = true;
  69499. var geometry = geometryRenderer.getGBuffer();
  69500. // Base post-process
  69501. 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));
  69502. var depthValues = BABYLON.Vector2.Zero();
  69503. this.volumetricLightPostProcess.onApply = function (effect) {
  69504. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69505. var generator = _this.sourceLight.getShadowGenerator();
  69506. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69507. effect.setTexture("positionSampler", geometry.textures[2]);
  69508. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69509. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69510. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69511. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69512. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69513. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69514. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69515. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69516. effect.setVector2("depthValues", depthValues);
  69517. }
  69518. };
  69519. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69520. // Smooth
  69521. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69522. // Merge
  69523. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69524. this.volumetricLightMergePostProces.onApply = function (effect) {
  69525. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69526. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69527. };
  69528. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69529. };
  69530. // Create luminance
  69531. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69532. var _this = this;
  69533. // Create luminance
  69534. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69535. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69536. var offsets = [];
  69537. this.luminancePostProcess.onApply = function (effect) {
  69538. var sU = (1.0 / _this.luminancePostProcess.width);
  69539. var sV = (1.0 / _this.luminancePostProcess.height);
  69540. offsets[0] = -0.5 * sU;
  69541. offsets[1] = 0.5 * sV;
  69542. offsets[2] = 0.5 * sU;
  69543. offsets[3] = 0.5 * sV;
  69544. offsets[4] = -0.5 * sU;
  69545. offsets[5] = -0.5 * sV;
  69546. offsets[6] = 0.5 * sU;
  69547. offsets[7] = -0.5 * sV;
  69548. effect.setArray2("lumOffsets", offsets);
  69549. };
  69550. // Add to pipeline
  69551. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69552. // Create down sample luminance
  69553. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69554. var size = Math.pow(3, i);
  69555. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69556. if (i === 0) {
  69557. defines += "#define FINAL_DOWN_SAMPLER";
  69558. }
  69559. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69560. this.luminanceDownSamplePostProcesses.push(postProcess);
  69561. }
  69562. // Create callbacks and add effects
  69563. var lastLuminance = this.luminancePostProcess;
  69564. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69565. var downSampleOffsets = new Array(18);
  69566. pp.onApply = function (effect) {
  69567. if (!lastLuminance) {
  69568. return;
  69569. }
  69570. var id = 0;
  69571. for (var x = -1; x < 2; x++) {
  69572. for (var y = -1; y < 2; y++) {
  69573. downSampleOffsets[id] = x / lastLuminance.width;
  69574. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69575. id += 2;
  69576. }
  69577. }
  69578. effect.setArray2("dsOffsets", downSampleOffsets);
  69579. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69580. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69581. lastLuminance = _this.luminancePostProcess;
  69582. }
  69583. else {
  69584. lastLuminance = pp;
  69585. }
  69586. };
  69587. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69588. pp.onAfterRender = function (effect) {
  69589. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69590. 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);
  69591. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69592. };
  69593. }
  69594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69595. });
  69596. };
  69597. // Create HDR post-process
  69598. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69599. var _this = this;
  69600. 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);
  69601. var outputLiminance = 1;
  69602. var time = 0;
  69603. var lastTime = 0;
  69604. this.hdrPostProcess.onApply = function (effect) {
  69605. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69606. time += scene.getEngine().getDeltaTime();
  69607. if (outputLiminance < 0) {
  69608. outputLiminance = _this._hdrCurrentLuminance;
  69609. }
  69610. else {
  69611. var dt = (lastTime - time) / 1000.0;
  69612. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69613. outputLiminance += _this.hdrDecreaseRate * dt;
  69614. }
  69615. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69616. outputLiminance -= _this.hdrIncreaseRate * dt;
  69617. }
  69618. else {
  69619. outputLiminance = _this._hdrCurrentLuminance;
  69620. }
  69621. }
  69622. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69623. effect.setFloat("averageLuminance", outputLiminance);
  69624. lastTime = time;
  69625. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69626. };
  69627. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69628. };
  69629. // Create lens flare post-process
  69630. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69631. var _this = this;
  69632. 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);
  69633. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69634. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69635. 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);
  69636. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69637. var resolution = new BABYLON.Vector2(0, 0);
  69638. // Lens flare
  69639. this.lensFlarePostProcess.onApply = function (effect) {
  69640. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69641. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69642. effect.setFloat("strength", _this.lensFlareStrength);
  69643. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69644. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69645. // Shift
  69646. resolution.x = _this.lensFlarePostProcess.width;
  69647. resolution.y = _this.lensFlarePostProcess.height;
  69648. effect.setVector2("resolution", resolution);
  69649. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69650. };
  69651. // Compose
  69652. 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);
  69653. 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);
  69654. this.lensFlareComposePostProcess.onApply = function (effect) {
  69655. if (!_this._scene.activeCamera) {
  69656. return;
  69657. }
  69658. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69659. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69660. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69661. // Lens start rotation matrix
  69662. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69663. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69664. 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));
  69665. camRot *= 4.0;
  69666. 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);
  69667. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69668. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69669. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69670. };
  69671. };
  69672. // Create depth-of-field post-process
  69673. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69674. var _this = this;
  69675. 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);
  69676. this.depthOfFieldPostProcess.onApply = function (effect) {
  69677. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69678. effect.setTexture("depthSampler", _this._getDepthTexture());
  69679. effect.setFloat("distance", _this.depthOfFieldDistance);
  69680. };
  69681. // Add to pipeline
  69682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69683. };
  69684. // Create motion blur post-process
  69685. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69686. var _this = this;
  69687. 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);
  69688. var motionScale = 0;
  69689. var prevViewProjection = BABYLON.Matrix.Identity();
  69690. var invViewProjection = BABYLON.Matrix.Identity();
  69691. var viewProjection = BABYLON.Matrix.Identity();
  69692. var screenSize = BABYLON.Vector2.Zero();
  69693. this.motionBlurPostProcess.onApply = function (effect) {
  69694. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69695. viewProjection.invertToRef(invViewProjection);
  69696. effect.setMatrix("inverseViewProjection", invViewProjection);
  69697. effect.setMatrix("prevViewProjection", prevViewProjection);
  69698. prevViewProjection = viewProjection;
  69699. screenSize.x = _this.motionBlurPostProcess.width;
  69700. screenSize.y = _this.motionBlurPostProcess.height;
  69701. effect.setVector2("screenSize", screenSize);
  69702. motionScale = scene.getEngine().getFps() / 60.0;
  69703. effect.setFloat("motionScale", motionScale);
  69704. effect.setFloat("motionStrength", _this.motionStrength);
  69705. effect.setTexture("depthSampler", _this._getDepthTexture());
  69706. };
  69707. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69708. };
  69709. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69710. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69711. var renderer = this._scene.enableGeometryBufferRenderer();
  69712. return renderer.getGBuffer().textures[0];
  69713. }
  69714. return this._scene.enableDepthRenderer().getDepthMap();
  69715. };
  69716. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69717. for (var i = 0; i < this._cameras.length; i++) {
  69718. var camera = this._cameras[i];
  69719. if (this.originalPostProcess) {
  69720. this.originalPostProcess.dispose(camera);
  69721. }
  69722. if (this.downSampleX4PostProcess) {
  69723. this.downSampleX4PostProcess.dispose(camera);
  69724. }
  69725. if (this.brightPassPostProcess) {
  69726. this.brightPassPostProcess.dispose(camera);
  69727. }
  69728. if (this.textureAdderPostProcess) {
  69729. this.textureAdderPostProcess.dispose(camera);
  69730. }
  69731. if (this.textureAdderFinalPostProcess) {
  69732. this.textureAdderFinalPostProcess.dispose(camera);
  69733. }
  69734. if (this.volumetricLightPostProcess) {
  69735. this.volumetricLightPostProcess.dispose(camera);
  69736. }
  69737. if (this.volumetricLightSmoothXPostProcess) {
  69738. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69739. }
  69740. if (this.volumetricLightSmoothYPostProcess) {
  69741. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69742. }
  69743. if (this.volumetricLightMergePostProces) {
  69744. this.volumetricLightMergePostProces.dispose(camera);
  69745. }
  69746. if (this.volumetricLightFinalPostProcess) {
  69747. this.volumetricLightFinalPostProcess.dispose(camera);
  69748. }
  69749. if (this.lensFlarePostProcess) {
  69750. this.lensFlarePostProcess.dispose(camera);
  69751. }
  69752. if (this.lensFlareComposePostProcess) {
  69753. this.lensFlareComposePostProcess.dispose(camera);
  69754. }
  69755. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69756. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69757. }
  69758. if (this.luminancePostProcess) {
  69759. this.luminancePostProcess.dispose(camera);
  69760. }
  69761. if (this.hdrPostProcess) {
  69762. this.hdrPostProcess.dispose(camera);
  69763. }
  69764. if (this.hdrFinalPostProcess) {
  69765. this.hdrFinalPostProcess.dispose(camera);
  69766. }
  69767. if (this.depthOfFieldPostProcess) {
  69768. this.depthOfFieldPostProcess.dispose(camera);
  69769. }
  69770. if (this.motionBlurPostProcess) {
  69771. this.motionBlurPostProcess.dispose(camera);
  69772. }
  69773. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69774. this.blurHPostProcesses[j].dispose(camera);
  69775. }
  69776. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69777. this.blurVPostProcesses[j].dispose(camera);
  69778. }
  69779. }
  69780. this.originalPostProcess = null;
  69781. this.downSampleX4PostProcess = null;
  69782. this.brightPassPostProcess = null;
  69783. this.textureAdderPostProcess = null;
  69784. this.textureAdderFinalPostProcess = null;
  69785. this.volumetricLightPostProcess = null;
  69786. this.volumetricLightSmoothXPostProcess = null;
  69787. this.volumetricLightSmoothYPostProcess = null;
  69788. this.volumetricLightMergePostProces = null;
  69789. this.volumetricLightFinalPostProcess = null;
  69790. this.lensFlarePostProcess = null;
  69791. this.lensFlareComposePostProcess = null;
  69792. this.luminancePostProcess = null;
  69793. this.hdrPostProcess = null;
  69794. this.hdrFinalPostProcess = null;
  69795. this.depthOfFieldPostProcess = null;
  69796. this.motionBlurPostProcess = null;
  69797. this.luminanceDownSamplePostProcesses = [];
  69798. this.blurHPostProcesses = [];
  69799. this.blurVPostProcesses = [];
  69800. };
  69801. // Dispose
  69802. StandardRenderingPipeline.prototype.dispose = function () {
  69803. this._disposePostProcesses();
  69804. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69805. _super.prototype.dispose.call(this);
  69806. };
  69807. // Serialize rendering pipeline
  69808. StandardRenderingPipeline.prototype.serialize = function () {
  69809. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69810. serializationObject.customType = "StandardRenderingPipeline";
  69811. return serializationObject;
  69812. };
  69813. /**
  69814. * Static members
  69815. */
  69816. // Parse serialized pipeline
  69817. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69818. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69819. };
  69820. // Luminance steps
  69821. StandardRenderingPipeline.LuminanceSteps = 6;
  69822. __decorate([
  69823. BABYLON.serialize()
  69824. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69825. __decorate([
  69826. BABYLON.serialize()
  69827. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69828. __decorate([
  69829. BABYLON.serialize()
  69830. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69831. __decorate([
  69832. BABYLON.serialize()
  69833. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69834. __decorate([
  69835. BABYLON.serializeAsTexture("lensTexture")
  69836. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69837. __decorate([
  69838. BABYLON.serialize()
  69839. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69840. __decorate([
  69841. BABYLON.serialize()
  69842. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69843. __decorate([
  69844. BABYLON.serialize()
  69845. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69846. __decorate([
  69847. BABYLON.serialize()
  69848. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69849. __decorate([
  69850. BABYLON.serialize()
  69851. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69852. __decorate([
  69853. BABYLON.serialize()
  69854. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69855. __decorate([
  69856. BABYLON.serializeAsTexture("lensColorTexture")
  69857. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69858. __decorate([
  69859. BABYLON.serialize()
  69860. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69861. __decorate([
  69862. BABYLON.serialize()
  69863. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69864. __decorate([
  69865. BABYLON.serialize()
  69866. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69867. __decorate([
  69868. BABYLON.serialize()
  69869. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69870. __decorate([
  69871. BABYLON.serializeAsTexture("lensStarTexture")
  69872. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69873. __decorate([
  69874. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69875. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69876. __decorate([
  69877. BABYLON.serialize()
  69878. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69879. __decorate([
  69880. BABYLON.serialize()
  69881. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69882. __decorate([
  69883. BABYLON.serialize()
  69884. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69885. __decorate([
  69886. BABYLON.serialize()
  69887. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69888. __decorate([
  69889. BABYLON.serialize()
  69890. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69891. __decorate([
  69892. BABYLON.serialize()
  69893. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69894. __decorate([
  69895. BABYLON.serialize()
  69896. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69897. __decorate([
  69898. BABYLON.serialize()
  69899. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69900. __decorate([
  69901. BABYLON.serialize()
  69902. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69903. __decorate([
  69904. BABYLON.serialize()
  69905. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69906. __decorate([
  69907. BABYLON.serialize()
  69908. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69909. __decorate([
  69910. BABYLON.serialize()
  69911. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69912. return StandardRenderingPipeline;
  69913. }(BABYLON.PostProcessRenderPipeline));
  69914. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69915. })(BABYLON || (BABYLON = {}));
  69916. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69917. "use strict";
  69918. var BABYLON;
  69919. (function (BABYLON) {
  69920. var FxaaPostProcess = /** @class */ (function (_super) {
  69921. __extends(FxaaPostProcess, _super);
  69922. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69923. if (camera === void 0) { camera = null; }
  69924. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69925. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69926. _this.onApplyObservable.add(function (effect) {
  69927. var texelSize = _this.texelSize;
  69928. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69929. });
  69930. return _this;
  69931. }
  69932. return FxaaPostProcess;
  69933. }(BABYLON.PostProcess));
  69934. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69935. })(BABYLON || (BABYLON = {}));
  69936. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69937. "use strict";
  69938. var BABYLON;
  69939. (function (BABYLON) {
  69940. /**
  69941. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69942. */
  69943. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69944. __extends(ChromaticAberrationPostProcess, _super);
  69945. /**
  69946. * Creates a new instance ChromaticAberrationPostProcess
  69947. * @param name The name of the effect.
  69948. * @param screenWidth The width of the screen to apply the effect on.
  69949. * @param screenHeight The height of the screen to apply the effect on.
  69950. * @param options The required width/height ratio to downsize to before computing the render pass.
  69951. * @param camera The camera to apply the render pass to.
  69952. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69953. * @param engine The engine which the post process will be applied. (default: current engine)
  69954. * @param reusable If the post process can be reused on the same frame. (default: false)
  69955. * @param textureType Type of textures used when performing the post process. (default: 0)
  69956. * @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)
  69957. */
  69958. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69959. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69960. if (blockCompilation === void 0) { blockCompilation = false; }
  69961. 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;
  69962. /**
  69963. * The amount of seperation of rgb channels (default: 30)
  69964. */
  69965. _this.aberrationAmount = 30;
  69966. /**
  69967. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69968. */
  69969. _this.radialIntensity = 0;
  69970. /**
  69971. * 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))
  69972. */
  69973. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69974. /**
  69975. * 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))
  69976. */
  69977. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69978. _this.onApplyObservable.add(function (effect) {
  69979. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69980. effect.setFloat('screen_width', screenWidth);
  69981. effect.setFloat('screen_height', screenHeight);
  69982. effect.setFloat('radialIntensity', _this.radialIntensity);
  69983. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69984. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69985. });
  69986. return _this;
  69987. }
  69988. return ChromaticAberrationPostProcess;
  69989. }(BABYLON.PostProcess));
  69990. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69991. })(BABYLON || (BABYLON = {}));
  69992. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69993. "use strict";
  69994. var BABYLON;
  69995. (function (BABYLON) {
  69996. /**
  69997. * The GrainPostProcess adds noise to the image at mid luminance levels
  69998. */
  69999. var GrainPostProcess = /** @class */ (function (_super) {
  70000. __extends(GrainPostProcess, _super);
  70001. /**
  70002. * Creates a new instance of @see GrainPostProcess
  70003. * @param name The name of the effect.
  70004. * @param options The required width/height ratio to downsize to before computing the render pass.
  70005. * @param camera The camera to apply the render pass to.
  70006. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70007. * @param engine The engine which the post process will be applied. (default: current engine)
  70008. * @param reusable If the post process can be reused on the same frame. (default: false)
  70009. * @param textureType Type of textures used when performing the post process. (default: 0)
  70010. * @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)
  70011. */
  70012. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70013. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70014. if (blockCompilation === void 0) { blockCompilation = false; }
  70015. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70016. /**
  70017. * The intensity of the grain added (default: 30)
  70018. */
  70019. _this.intensity = 30;
  70020. /**
  70021. * If the grain should be randomized on every frame
  70022. */
  70023. _this.animated = false;
  70024. _this.onApplyObservable.add(function (effect) {
  70025. effect.setFloat('intensity', _this.intensity);
  70026. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  70027. });
  70028. return _this;
  70029. }
  70030. return GrainPostProcess;
  70031. }(BABYLON.PostProcess));
  70032. BABYLON.GrainPostProcess = GrainPostProcess;
  70033. })(BABYLON || (BABYLON = {}));
  70034. //# sourceMappingURL=babylon.grainPostProcess.js.map
  70035. "use strict";
  70036. var BABYLON;
  70037. (function (BABYLON) {
  70038. /**
  70039. * The SharpenPostProcess applies a sharpen kernel to every pixel
  70040. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70041. */
  70042. var SharpenPostProcess = /** @class */ (function (_super) {
  70043. __extends(SharpenPostProcess, _super);
  70044. /**
  70045. * Creates a new instance ConvolutionPostProcess
  70046. * @param name The name of the effect.
  70047. * @param options The required width/height ratio to downsize to before computing the render pass.
  70048. * @param camera The camera to apply the render pass to.
  70049. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70050. * @param engine The engine which the post process will be applied. (default: current engine)
  70051. * @param reusable If the post process can be reused on the same frame. (default: false)
  70052. * @param textureType Type of textures used when performing the post process. (default: 0)
  70053. * @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)
  70054. */
  70055. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70056. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70057. if (blockCompilation === void 0) { blockCompilation = false; }
  70058. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70059. /**
  70060. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  70061. */
  70062. _this.colorAmount = 1.0;
  70063. /**
  70064. * How much sharpness should be applied (default: 0.3)
  70065. */
  70066. _this.edgeAmount = 0.3;
  70067. _this.onApply = function (effect) {
  70068. effect.setFloat2("screenSize", _this.width, _this.height);
  70069. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  70070. };
  70071. return _this;
  70072. }
  70073. return SharpenPostProcess;
  70074. }(BABYLON.PostProcess));
  70075. BABYLON.SharpenPostProcess = SharpenPostProcess;
  70076. })(BABYLON || (BABYLON = {}));
  70077. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  70078. "use strict";
  70079. var BABYLON;
  70080. (function (BABYLON) {
  70081. /**
  70082. * The Blur Post Process which blurs an image based on a kernel and direction.
  70083. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70084. */
  70085. var BlurPostProcess = /** @class */ (function (_super) {
  70086. __extends(BlurPostProcess, _super);
  70087. /**
  70088. * Creates a new instance BlurPostProcess
  70089. * @param name The name of the effect.
  70090. * @param direction The direction in which to blur the image.
  70091. * @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.
  70092. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70093. * @param camera The camera to apply the render pass to.
  70094. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70095. * @param engine The engine which the post process will be applied. (default: current engine)
  70096. * @param reusable If the post process can be reused on the same frame. (default: false)
  70097. * @param textureType Type of textures used when performing the post process. (default: 0)
  70098. * @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)
  70099. */
  70100. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70101. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70102. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70103. if (defines === void 0) { defines = ""; }
  70104. if (blockCompilation === void 0) { blockCompilation = false; }
  70105. 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;
  70106. _this.direction = direction;
  70107. _this.blockCompilation = blockCompilation;
  70108. _this._packedFloat = false;
  70109. _this._staticDefines = "";
  70110. _this._staticDefines = defines;
  70111. _this.onApplyObservable.add(function (effect) {
  70112. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70113. });
  70114. _this.kernel = kernel;
  70115. return _this;
  70116. }
  70117. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70118. /**
  70119. * Gets the length in pixels of the blur sample region
  70120. */
  70121. get: function () {
  70122. return this._idealKernel;
  70123. },
  70124. /**
  70125. * Sets the length in pixels of the blur sample region
  70126. */
  70127. set: function (v) {
  70128. if (this._idealKernel === v) {
  70129. return;
  70130. }
  70131. v = Math.max(v, 1);
  70132. this._idealKernel = v;
  70133. this._kernel = this._nearestBestKernel(v);
  70134. if (!this.blockCompilation) {
  70135. this._updateParameters();
  70136. }
  70137. },
  70138. enumerable: true,
  70139. configurable: true
  70140. });
  70141. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70142. /**
  70143. * Gets wether or not the blur is unpacking/repacking floats
  70144. */
  70145. get: function () {
  70146. return this._packedFloat;
  70147. },
  70148. /**
  70149. * Sets wether or not the blur needs to unpack/repack floats
  70150. */
  70151. set: function (v) {
  70152. if (this._packedFloat === v) {
  70153. return;
  70154. }
  70155. this._packedFloat = v;
  70156. if (!this.blockCompilation) {
  70157. this._updateParameters();
  70158. }
  70159. },
  70160. enumerable: true,
  70161. configurable: true
  70162. });
  70163. /**
  70164. * Updates the effect with the current post process compile time values and recompiles the shader.
  70165. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70166. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70167. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70168. * @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
  70169. * @param onCompiled Called when the shader has been compiled.
  70170. * @param onError Called if there is an error when compiling a shader.
  70171. */
  70172. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70173. if (defines === void 0) { defines = null; }
  70174. if (uniforms === void 0) { uniforms = null; }
  70175. if (samplers === void 0) { samplers = null; }
  70176. this._updateParameters(onCompiled, onError);
  70177. };
  70178. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70179. // Generate sampling offsets and weights
  70180. var N = this._kernel;
  70181. var centerIndex = (N - 1) / 2;
  70182. // Generate Gaussian sampling weights over kernel
  70183. var offsets = [];
  70184. var weights = [];
  70185. var totalWeight = 0;
  70186. for (var i = 0; i < N; i++) {
  70187. var u = i / (N - 1);
  70188. var w = this._gaussianWeight(u * 2.0 - 1);
  70189. offsets[i] = (i - centerIndex);
  70190. weights[i] = w;
  70191. totalWeight += w;
  70192. }
  70193. // Normalize weights
  70194. for (var i = 0; i < weights.length; i++) {
  70195. weights[i] /= totalWeight;
  70196. }
  70197. // Optimize: combine samples to take advantage of hardware linear sampling
  70198. // Walk from left to center, combining pairs (symmetrically)
  70199. var linearSamplingWeights = [];
  70200. var linearSamplingOffsets = [];
  70201. var linearSamplingMap = [];
  70202. for (var i = 0; i <= centerIndex; i += 2) {
  70203. var j = Math.min(i + 1, Math.floor(centerIndex));
  70204. var singleCenterSample = i === j;
  70205. if (singleCenterSample) {
  70206. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70207. }
  70208. else {
  70209. var sharedCell = j === centerIndex;
  70210. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70211. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70212. if (offsetLinear === 0) {
  70213. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70214. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70215. }
  70216. else {
  70217. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70218. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70219. }
  70220. }
  70221. }
  70222. for (var i = 0; i < linearSamplingMap.length; i++) {
  70223. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70224. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70225. }
  70226. // Replace with optimized
  70227. offsets = linearSamplingOffsets;
  70228. weights = linearSamplingWeights;
  70229. // Generate shaders
  70230. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70231. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70232. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70233. var defines = "";
  70234. defines += this._staticDefines;
  70235. for (var i = 0; i < varyingCount; i++) {
  70236. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70237. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70238. }
  70239. var depCount = 0;
  70240. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70241. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70242. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70243. depCount++;
  70244. }
  70245. if (this.packedFloat) {
  70246. defines += "#define PACKEDFLOAT 1";
  70247. }
  70248. this.blockCompilation = false;
  70249. _super.prototype.updateEffect.call(this, defines, null, null, {
  70250. varyingCount: varyingCount,
  70251. depCount: depCount
  70252. }, onCompiled, onError);
  70253. };
  70254. /**
  70255. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70256. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70257. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70258. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70259. * The gaps between physical kernels are compensated for in the weighting of the samples
  70260. * @param idealKernel Ideal blur kernel.
  70261. * @return Nearest best kernel.
  70262. */
  70263. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70264. var v = Math.round(idealKernel);
  70265. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70266. var k = _a[_i];
  70267. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70268. return Math.max(k, 3);
  70269. }
  70270. }
  70271. return Math.max(v, 3);
  70272. };
  70273. /**
  70274. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70275. * @param x The point on the Gaussian distribution to sample.
  70276. * @return the value of the Gaussian function at x.
  70277. */
  70278. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70279. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70280. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70281. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70282. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70283. // truncated at around 1.3% of peak strength.
  70284. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70285. var sigma = (1 / 3);
  70286. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70287. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70288. var weight = (1.0 / denominator) * Math.exp(exponent);
  70289. return weight;
  70290. };
  70291. /**
  70292. * Generates a string that can be used as a floating point number in GLSL.
  70293. * @param x Value to print.
  70294. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70295. * @return GLSL float string.
  70296. */
  70297. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70298. if (decimalFigures === void 0) { decimalFigures = 8; }
  70299. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70300. };
  70301. return BlurPostProcess;
  70302. }(BABYLON.PostProcess));
  70303. BABYLON.BlurPostProcess = BlurPostProcess;
  70304. })(BABYLON || (BABYLON = {}));
  70305. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70306. "use strict";
  70307. var BABYLON;
  70308. (function (BABYLON) {
  70309. /**
  70310. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70311. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70312. * based on samples that have a large difference in distance than the center pixel.
  70313. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70314. */
  70315. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70316. __extends(DepthOfFieldBlurPostProcess, _super);
  70317. /**
  70318. * Creates a new instance CircleOfConfusionPostProcess
  70319. * @param name The name of the effect.
  70320. * @param scene The scene the effect belongs to.
  70321. * @param direction The direction the blur should be applied.
  70322. * @param kernel The size of the kernel used to blur.
  70323. * @param options The required width/height ratio to downsize to before computing the render pass.
  70324. * @param camera The camera to apply the render pass to.
  70325. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70326. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70327. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70328. * @param engine The engine which the post process will be applied. (default: current engine)
  70329. * @param reusable If the post process can be reused on the same frame. (default: false)
  70330. * @param textureType Type of textures used when performing the post process. (default: 0)
  70331. * @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)
  70332. */
  70333. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70334. if (imageToBlur === void 0) { imageToBlur = null; }
  70335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70336. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70337. if (blockCompilation === void 0) { blockCompilation = false; }
  70338. 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;
  70339. _this.direction = direction;
  70340. _this.onApplyObservable.add(function (effect) {
  70341. if (imageToBlur != null) {
  70342. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70343. }
  70344. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70345. if (scene.activeCamera) {
  70346. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70347. }
  70348. });
  70349. return _this;
  70350. }
  70351. return DepthOfFieldBlurPostProcess;
  70352. }(BABYLON.BlurPostProcess));
  70353. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70354. })(BABYLON || (BABYLON = {}));
  70355. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70356. "use strict";
  70357. var BABYLON;
  70358. (function (BABYLON) {
  70359. /**
  70360. * Options to be set when merging outputs from the default pipeline.
  70361. */
  70362. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  70363. function DepthOfFieldMergePostProcessOptions() {
  70364. }
  70365. return DepthOfFieldMergePostProcessOptions;
  70366. }());
  70367. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  70368. /**
  70369. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70370. */
  70371. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70372. __extends(DepthOfFieldMergePostProcess, _super);
  70373. /**
  70374. <<<<<<< HEAD
  70375. * Creates a new instance CircleOfConfusionPostProcess
  70376. =======
  70377. * Creates a new instance of @see DepthOfFieldMergePostProcess
  70378. >>>>>>> 70d3435c5f934f0416dfbf106f59fe53aacc8393
  70379. * @param name The name of the effect.
  70380. * @param originalFromInput Post process which's input will be used for the merge.
  70381. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  70382. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  70383. * @param options The required width/height ratio to downsize to before computing the render pass.
  70384. * @param camera The camera to apply the render pass to.
  70385. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70386. * @param engine The engine which the post process will be applied. (default: current engine)
  70387. * @param reusable If the post process can be reused on the same frame. (default: false)
  70388. * @param textureType Type of textures used when performing the post process. (default: 0)
  70389. * @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)
  70390. */
  70391. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70392. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70393. if (blockCompilation === void 0) { blockCompilation = false; }
  70394. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70395. _this.blurSteps = blurSteps;
  70396. _this.onApplyObservable.add(function (effect) {
  70397. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70398. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70399. blurSteps.forEach(function (step, index) {
  70400. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70401. });
  70402. });
  70403. if (!blockCompilation) {
  70404. _this.updateEffect();
  70405. }
  70406. return _this;
  70407. }
  70408. /**
  70409. * Updates the effect with the current post process compile time values and recompiles the shader.
  70410. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70411. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70412. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70413. * @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
  70414. * @param onCompiled Called when the shader has been compiled.
  70415. * @param onError Called if there is an error when compiling a shader.
  70416. */
  70417. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70418. if (defines === void 0) { defines = null; }
  70419. if (uniforms === void 0) { uniforms = null; }
  70420. if (samplers === void 0) { samplers = null; }
  70421. if (!defines) {
  70422. defines = "";
  70423. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  70424. }
  70425. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  70426. };
  70427. return DepthOfFieldMergePostProcess;
  70428. }(BABYLON.PostProcess));
  70429. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70430. })(BABYLON || (BABYLON = {}));
  70431. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70432. "use strict";
  70433. var BABYLON;
  70434. (function (BABYLON) {
  70435. /**
  70436. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70437. */
  70438. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70439. __extends(CircleOfConfusionPostProcess, _super);
  70440. /**
  70441. * Creates a new instance CircleOfConfusionPostProcess
  70442. * @param name The name of the effect.
  70443. * @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.
  70444. * @param options The required width/height ratio to downsize to before computing the render pass.
  70445. * @param camera The camera to apply the render pass to.
  70446. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70447. * @param engine The engine which the post process will be applied. (default: current engine)
  70448. * @param reusable If the post process can be reused on the same frame. (default: false)
  70449. * @param textureType Type of textures used when performing the post process. (default: 0)
  70450. * @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)
  70451. */
  70452. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70453. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70454. if (blockCompilation === void 0) { blockCompilation = false; }
  70455. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70456. /**
  70457. * 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.
  70458. */
  70459. _this.lensSize = 50;
  70460. /**
  70461. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70462. */
  70463. _this.fStop = 1.4;
  70464. /**
  70465. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70466. */
  70467. _this.focusDistance = 2000;
  70468. /**
  70469. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70470. */
  70471. _this.focalLength = 50;
  70472. _this._depthTexture = null;
  70473. _this._depthTexture = depthTexture;
  70474. _this.onApplyObservable.add(function (effect) {
  70475. if (!_this._depthTexture) {
  70476. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70477. return;
  70478. }
  70479. effect.setTexture("depthSampler", _this._depthTexture);
  70480. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70481. var aperture = _this.lensSize / _this.fStop;
  70482. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70483. effect.setFloat('focusDistance', _this.focusDistance);
  70484. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70485. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70486. });
  70487. return _this;
  70488. }
  70489. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70490. /**
  70491. * 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.
  70492. */
  70493. set: function (value) {
  70494. this._depthTexture = value;
  70495. },
  70496. enumerable: true,
  70497. configurable: true
  70498. });
  70499. return CircleOfConfusionPostProcess;
  70500. }(BABYLON.PostProcess));
  70501. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70502. })(BABYLON || (BABYLON = {}));
  70503. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70504. "use strict";
  70505. var BABYLON;
  70506. (function (BABYLON) {
  70507. /**
  70508. * Specifies the level of max blur that should be applied when using the depth of field effect
  70509. */
  70510. var DepthOfFieldEffectBlurLevel;
  70511. (function (DepthOfFieldEffectBlurLevel) {
  70512. /**
  70513. * Subtle blur
  70514. */
  70515. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70516. /**
  70517. * Medium blur
  70518. */
  70519. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70520. /**
  70521. * Large blur
  70522. */
  70523. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70524. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70525. ;
  70526. /**
  70527. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70528. */
  70529. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70530. __extends(DepthOfFieldEffect, _super);
  70531. /**
  70532. * Creates a new instance DepthOfFieldEffect
  70533. * @param scene The scene the effect belongs to.
  70534. * @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.
  70535. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70536. * @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)
  70537. */
  70538. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70539. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70540. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70541. if (blockCompilation === void 0) { blockCompilation = false; }
  70542. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70543. return _this._effects;
  70544. }, true) || this;
  70545. /**
  70546. * Internal post processes in depth of field effect
  70547. */
  70548. _this._effects = [];
  70549. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70550. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70551. // 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)
  70552. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70553. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70554. _this._depthOfFieldBlurY = [];
  70555. _this._depthOfFieldBlurX = [];
  70556. var blurCount = 1;
  70557. var kernelSize = 15;
  70558. switch (blurLevel) {
  70559. case DepthOfFieldEffectBlurLevel.High: {
  70560. blurCount = 3;
  70561. kernelSize = 51;
  70562. break;
  70563. }
  70564. case DepthOfFieldEffectBlurLevel.Medium: {
  70565. blurCount = 2;
  70566. kernelSize = 31;
  70567. break;
  70568. }
  70569. default: {
  70570. kernelSize = 15;
  70571. blurCount = 1;
  70572. break;
  70573. }
  70574. }
  70575. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70576. for (var i = 0; i < blurCount; i++) {
  70577. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70578. blurY.autoClear = false;
  70579. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70580. blurX.autoClear = false;
  70581. _this._depthOfFieldBlurY.push(blurY);
  70582. _this._depthOfFieldBlurX.push(blurX);
  70583. }
  70584. // Set all post processes on the effect.
  70585. _this._effects = [_this._circleOfConfusion];
  70586. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70587. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70588. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70589. }
  70590. // Merge blurred images with original image based on circleOfConfusion
  70591. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70592. _this._dofMerge.autoClear = false;
  70593. _this._effects.push(_this._dofMerge);
  70594. return _this;
  70595. }
  70596. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70597. get: function () {
  70598. return this._circleOfConfusion.focalLength;
  70599. },
  70600. /**
  70601. * The focal the length of the camera used in the effect
  70602. */
  70603. set: function (value) {
  70604. this._circleOfConfusion.focalLength = value;
  70605. },
  70606. enumerable: true,
  70607. configurable: true
  70608. });
  70609. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70610. get: function () {
  70611. return this._circleOfConfusion.fStop;
  70612. },
  70613. /**
  70614. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70615. */
  70616. set: function (value) {
  70617. this._circleOfConfusion.fStop = value;
  70618. },
  70619. enumerable: true,
  70620. configurable: true
  70621. });
  70622. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70623. get: function () {
  70624. return this._circleOfConfusion.focusDistance;
  70625. },
  70626. /**
  70627. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70628. */
  70629. set: function (value) {
  70630. this._circleOfConfusion.focusDistance = value;
  70631. },
  70632. enumerable: true,
  70633. configurable: true
  70634. });
  70635. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70636. get: function () {
  70637. return this._circleOfConfusion.lensSize;
  70638. },
  70639. /**
  70640. * 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.
  70641. */
  70642. set: function (value) {
  70643. this._circleOfConfusion.lensSize = value;
  70644. },
  70645. enumerable: true,
  70646. configurable: true
  70647. });
  70648. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70649. /**
  70650. * 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.
  70651. */
  70652. set: function (value) {
  70653. this._circleOfConfusion.depthTexture = value;
  70654. },
  70655. enumerable: true,
  70656. configurable: true
  70657. });
  70658. /**
  70659. * Disposes each of the internal effects for a given camera.
  70660. * @param camera The camera to dispose the effect on.
  70661. */
  70662. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70663. for (var effect in this._effects) {
  70664. this._effects[effect].dispose(camera);
  70665. }
  70666. };
  70667. /**
  70668. * Internal
  70669. */
  70670. DepthOfFieldEffect.prototype._updateEffects = function () {
  70671. for (var effect in this._effects) {
  70672. this._effects[effect].updateEffect();
  70673. }
  70674. };
  70675. /**
  70676. * Internal
  70677. * @returns if all the contained post processes are ready.
  70678. */
  70679. DepthOfFieldEffect.prototype._isReady = function () {
  70680. for (var effect in this._effects) {
  70681. if (!this._effects[effect].isReady()) {
  70682. return false;
  70683. }
  70684. }
  70685. return true;
  70686. };
  70687. return DepthOfFieldEffect;
  70688. }(BABYLON.PostProcessRenderEffect));
  70689. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70690. })(BABYLON || (BABYLON = {}));
  70691. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70692. "use strict";
  70693. var BABYLON;
  70694. (function (BABYLON) {
  70695. /**
  70696. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70697. */
  70698. var BloomMergePostProcess = /** @class */ (function (_super) {
  70699. __extends(BloomMergePostProcess, _super);
  70700. /**
  70701. * Creates a new instance of @see BloomMergePostProcess
  70702. * @param name The name of the effect.
  70703. * @param originalFromInput Post process which's input will be used for the merge.
  70704. * @param blurred Blurred highlights post process which's output will be used.
  70705. * @param weight Weight of the bloom to be added to the original input.
  70706. * @param options The required width/height ratio to downsize to before computing the render pass.
  70707. * @param camera The camera to apply the render pass to.
  70708. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70709. * @param engine The engine which the post process will be applied. (default: current engine)
  70710. * @param reusable If the post process can be reused on the same frame. (default: false)
  70711. * @param textureType Type of textures used when performing the post process. (default: 0)
  70712. * @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)
  70713. */
  70714. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70715. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70716. if (blockCompilation === void 0) { blockCompilation = false; }
  70717. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70718. _this.weight = weight;
  70719. _this.onApplyObservable.add(function (effect) {
  70720. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70721. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  70722. effect.setFloat("bloomWeight", _this.weight);
  70723. });
  70724. if (!blockCompilation) {
  70725. _this.updateEffect();
  70726. }
  70727. return _this;
  70728. }
  70729. return BloomMergePostProcess;
  70730. }(BABYLON.PostProcess));
  70731. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  70732. })(BABYLON || (BABYLON = {}));
  70733. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  70734. "use strict";
  70735. var BABYLON;
  70736. (function (BABYLON) {
  70737. /**
  70738. * 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.
  70739. */
  70740. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  70741. __extends(ExtractHighlightsPostProcess, _super);
  70742. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70743. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70744. if (blockCompilation === void 0) { blockCompilation = false; }
  70745. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70746. /**
  70747. * The luminance threshold, pixels below this value will be set to black.
  70748. */
  70749. _this.threshold = 0.9;
  70750. /**
  70751. * Internal
  70752. */
  70753. _this._exposure = 1;
  70754. /**
  70755. * Post process which has the input texture to be used when performing highlight extraction
  70756. */
  70757. _this._inputPostProcess = null;
  70758. _this.onApplyObservable.add(function (effect) {
  70759. if (_this._inputPostProcess) {
  70760. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  70761. }
  70762. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  70763. effect.setFloat('exposure', _this._exposure);
  70764. });
  70765. return _this;
  70766. }
  70767. return ExtractHighlightsPostProcess;
  70768. }(BABYLON.PostProcess));
  70769. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  70770. })(BABYLON || (BABYLON = {}));
  70771. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  70772. "use strict";
  70773. var BABYLON;
  70774. (function (BABYLON) {
  70775. /**
  70776. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  70777. */
  70778. var BloomEffect = /** @class */ (function (_super) {
  70779. __extends(BloomEffect, _super);
  70780. /**
  70781. * Creates a new instance of @see BloomEffect
  70782. * @param scene The scene the effect belongs to.
  70783. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  70784. * @param bloomKernel The size of the kernel to be used when applying the blur.
  70785. * @param bloomWeight The the strength of bloom.
  70786. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70787. * @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)
  70788. */
  70789. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  70790. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70791. if (blockCompilation === void 0) { blockCompilation = false; }
  70792. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  70793. return _this._effects;
  70794. }, true) || this;
  70795. _this.bloomScale = bloomScale;
  70796. /**
  70797. * Internal
  70798. */
  70799. _this._effects = [];
  70800. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70801. _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);
  70802. _this._blurX.alwaysForcePOT = true;
  70803. _this._blurX.autoClear = false;
  70804. _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);
  70805. _this._blurY.alwaysForcePOT = true;
  70806. _this._blurY.autoClear = false;
  70807. _this.kernel = bloomKernel;
  70808. _this._upscale = new BABYLON.PassPostProcess("upscale", bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70809. _this._upscale.autoClear = false;
  70810. _this._effects = [_this._downscale, _this._blurX, _this._blurY, _this._upscale];
  70811. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70812. _this._merge.autoClear = false;
  70813. _this._effects.push(_this._merge);
  70814. return _this;
  70815. }
  70816. Object.defineProperty(BloomEffect.prototype, "threshold", {
  70817. /**
  70818. * The luminance threshold to find bright areas of the image to bloom.
  70819. */
  70820. get: function () {
  70821. return this._downscale.threshold;
  70822. },
  70823. set: function (value) {
  70824. this._downscale.threshold = value;
  70825. },
  70826. enumerable: true,
  70827. configurable: true
  70828. });
  70829. Object.defineProperty(BloomEffect.prototype, "weight", {
  70830. /**
  70831. * The strength of the bloom.
  70832. */
  70833. get: function () {
  70834. return this._merge.weight;
  70835. },
  70836. set: function (value) {
  70837. this._merge.weight = value;
  70838. },
  70839. enumerable: true,
  70840. configurable: true
  70841. });
  70842. Object.defineProperty(BloomEffect.prototype, "kernel", {
  70843. /**
  70844. * Specifies the size of the bloom blur kernel, relative to the final output size
  70845. */
  70846. get: function () {
  70847. return this._blurX.kernel / this.bloomScale;
  70848. },
  70849. set: function (value) {
  70850. this._blurX.kernel = value * this.bloomScale;
  70851. this._blurY.kernel = value * this.bloomScale;
  70852. },
  70853. enumerable: true,
  70854. configurable: true
  70855. });
  70856. /**
  70857. * Disposes each of the internal effects for a given camera.
  70858. * @param camera The camera to dispose the effect on.
  70859. */
  70860. BloomEffect.prototype.disposeEffects = function (camera) {
  70861. for (var effect in this._effects) {
  70862. this._effects[effect].dispose(camera);
  70863. }
  70864. };
  70865. /**
  70866. * Internal
  70867. */
  70868. BloomEffect.prototype._updateEffects = function () {
  70869. for (var effect in this._effects) {
  70870. this._effects[effect].updateEffect();
  70871. }
  70872. };
  70873. /**
  70874. * Internal
  70875. * @returns if all the contained post processes are ready.
  70876. */
  70877. BloomEffect.prototype._isReady = function () {
  70878. for (var effect in this._effects) {
  70879. if (!this._effects[effect].isReady()) {
  70880. return false;
  70881. }
  70882. }
  70883. return true;
  70884. };
  70885. return BloomEffect;
  70886. }(BABYLON.PostProcessRenderEffect));
  70887. BABYLON.BloomEffect = BloomEffect;
  70888. })(BABYLON || (BABYLON = {}));
  70889. //# sourceMappingURL=babylon.bloomEffect.js.map
  70890. "use strict";
  70891. var BABYLON;
  70892. (function (BABYLON) {
  70893. /**
  70894. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70895. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70896. */
  70897. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70898. __extends(DefaultRenderingPipeline, _super);
  70899. /**
  70900. * @constructor
  70901. * @param {string} name - The rendering pipeline name
  70902. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70903. * @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)
  70904. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70905. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70906. */
  70907. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70908. if (automaticBuild === void 0) { automaticBuild = true; }
  70909. var _this = _super.call(this, scene.getEngine(), name) || this;
  70910. _this._originalCameras = [];
  70911. /**
  70912. * ID of the sharpen post process,
  70913. */
  70914. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70915. /**
  70916. * ID of the image processing post process;
  70917. */
  70918. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70919. /**
  70920. * ID of the Fast Approximate Anti-Aliasing post process;
  70921. */
  70922. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70923. /**
  70924. * ID of the chromatic aberration post process,
  70925. */
  70926. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70927. /**
  70928. * ID of the grain post process
  70929. */
  70930. _this.GrainPostProcessId = "GrainPostProcessEffect";
  70931. /**
  70932. * Animations which can be used to tweak settings over a period of time
  70933. */
  70934. _this.animations = [];
  70935. _this._imageProcessingConfigurationObserver = null;
  70936. // Values
  70937. _this._sharpenEnabled = false;
  70938. _this._bloomEnabled = false;
  70939. _this._depthOfFieldEnabled = false;
  70940. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70941. _this._fxaaEnabled = false;
  70942. _this._imageProcessingEnabled = true;
  70943. _this._bloomScale = 0.5;
  70944. _this._chromaticAberrationEnabled = false;
  70945. _this._grainEnabled = false;
  70946. _this._buildAllowed = true;
  70947. _this._resizeObserver = null;
  70948. _this._hardwareScaleLevel = 1.0;
  70949. _this._bloomKernel = 64;
  70950. /**
  70951. * Specifies the weight of the bloom in the final rendering
  70952. */
  70953. _this._bloomWeight = 0.15;
  70954. /**
  70955. * Specifies the luma threshold for the area that will be blurred by the bloom
  70956. */
  70957. _this._bloomThreshold = 0.9;
  70958. _this._samples = 1;
  70959. _this._hasCleared = false;
  70960. _this._prevPostProcess = null;
  70961. _this._prevPrevPostProcess = null;
  70962. _this._cameras = cameras || [];
  70963. _this._originalCameras = _this._cameras.slice();
  70964. _this._buildAllowed = automaticBuild;
  70965. // Initialize
  70966. _this._scene = scene;
  70967. var caps = _this._scene.getEngine().getCaps();
  70968. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70969. // Misc
  70970. if (_this._hdr) {
  70971. if (caps.textureHalfFloatRender) {
  70972. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70973. }
  70974. else if (caps.textureFloatRender) {
  70975. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70976. }
  70977. }
  70978. else {
  70979. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70980. }
  70981. // Attach
  70982. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70983. var engine = _this._scene.getEngine();
  70984. // Create post processes before hand so they can be modified before enabled.
  70985. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70986. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70987. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70988. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70989. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  70990. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70991. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70992. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70993. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  70994. _this._resizeObserver = engine.onResizeObservable.add(function () {
  70995. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  70996. _this.bloomKernel = _this.bloomKernel;
  70997. });
  70998. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70999. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  71000. });
  71001. _this._buildPipeline();
  71002. return _this;
  71003. }
  71004. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  71005. get: function () {
  71006. return this._sharpenEnabled;
  71007. },
  71008. /**
  71009. * Enable or disable the sharpen process from the pipeline
  71010. */
  71011. set: function (enabled) {
  71012. if (this._sharpenEnabled === enabled) {
  71013. return;
  71014. }
  71015. this._sharpenEnabled = enabled;
  71016. this._buildPipeline();
  71017. },
  71018. enumerable: true,
  71019. configurable: true
  71020. });
  71021. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  71022. /**
  71023. * Specifies the size of the bloom blur kernel, relative to the final output size
  71024. */
  71025. get: function () {
  71026. return this._bloomKernel;
  71027. },
  71028. set: function (value) {
  71029. this._bloomKernel = value;
  71030. this.bloom.kernel = value / this._hardwareScaleLevel;
  71031. },
  71032. enumerable: true,
  71033. configurable: true
  71034. });
  71035. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  71036. get: function () {
  71037. return this._bloomWeight;
  71038. },
  71039. /**
  71040. * The strength of the bloom.
  71041. */
  71042. set: function (value) {
  71043. if (this._bloomWeight === value) {
  71044. return;
  71045. }
  71046. this.bloom.weight = value;
  71047. this._bloomWeight = value;
  71048. },
  71049. enumerable: true,
  71050. configurable: true
  71051. });
  71052. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  71053. get: function () {
  71054. return this._bloomThreshold;
  71055. },
  71056. /**
  71057. * The strength of the bloom.
  71058. */
  71059. set: function (value) {
  71060. if (this._bloomThreshold === value) {
  71061. return;
  71062. }
  71063. this.bloom.threshold = value;
  71064. this._bloomThreshold = value;
  71065. },
  71066. enumerable: true,
  71067. configurable: true
  71068. });
  71069. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  71070. get: function () {
  71071. return this._bloomScale;
  71072. },
  71073. /**
  71074. * The scale of the bloom, lower value will provide better performance.
  71075. */
  71076. set: function (value) {
  71077. if (this._bloomScale === value) {
  71078. return;
  71079. }
  71080. this._bloomScale = value;
  71081. // recreate bloom and dispose old as this setting is not dynamic
  71082. this._rebuildBloom();
  71083. this._buildPipeline();
  71084. },
  71085. enumerable: true,
  71086. configurable: true
  71087. });
  71088. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  71089. get: function () {
  71090. return this._bloomEnabled;
  71091. },
  71092. /**
  71093. * Enable or disable the bloom from the pipeline
  71094. */
  71095. set: function (enabled) {
  71096. if (this._bloomEnabled === enabled) {
  71097. return;
  71098. }
  71099. this._bloomEnabled = enabled;
  71100. this._buildPipeline();
  71101. },
  71102. enumerable: true,
  71103. configurable: true
  71104. });
  71105. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  71106. // recreate bloom and dispose old as this setting is not dynamic
  71107. var oldBloom = this.bloom;
  71108. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  71109. this.bloom.threshold = oldBloom.threshold;
  71110. for (var i = 0; i < this._cameras.length; i++) {
  71111. oldBloom.disposeEffects(this._cameras[i]);
  71112. }
  71113. };
  71114. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  71115. /**
  71116. * If the depth of field is enabled.
  71117. */
  71118. get: function () {
  71119. return this._depthOfFieldEnabled;
  71120. },
  71121. set: function (enabled) {
  71122. if (this._depthOfFieldEnabled === enabled) {
  71123. return;
  71124. }
  71125. this._depthOfFieldEnabled = enabled;
  71126. this._buildPipeline();
  71127. },
  71128. enumerable: true,
  71129. configurable: true
  71130. });
  71131. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  71132. /**
  71133. * Blur level of the depth of field effect. (Higher blur will effect performance)
  71134. */
  71135. get: function () {
  71136. return this._depthOfFieldBlurLevel;
  71137. },
  71138. set: function (value) {
  71139. if (this._depthOfFieldBlurLevel === value) {
  71140. return;
  71141. }
  71142. this._depthOfFieldBlurLevel = value;
  71143. // recreate dof and dispose old as this setting is not dynamic
  71144. var oldDof = this.depthOfField;
  71145. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  71146. this.depthOfField.focalLength = oldDof.focalLength;
  71147. this.depthOfField.focusDistance = oldDof.focusDistance;
  71148. this.depthOfField.fStop = oldDof.fStop;
  71149. this.depthOfField.lensSize = oldDof.lensSize;
  71150. for (var i = 0; i < this._cameras.length; i++) {
  71151. oldDof.disposeEffects(this._cameras[i]);
  71152. }
  71153. this._buildPipeline();
  71154. },
  71155. enumerable: true,
  71156. configurable: true
  71157. });
  71158. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  71159. get: function () {
  71160. return this._fxaaEnabled;
  71161. },
  71162. /**
  71163. * If the anti aliasing is enabled.
  71164. */
  71165. set: function (enabled) {
  71166. if (this._fxaaEnabled === enabled) {
  71167. return;
  71168. }
  71169. this._fxaaEnabled = enabled;
  71170. this._buildPipeline();
  71171. },
  71172. enumerable: true,
  71173. configurable: true
  71174. });
  71175. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  71176. get: function () {
  71177. return this._samples;
  71178. },
  71179. /**
  71180. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  71181. */
  71182. set: function (sampleCount) {
  71183. if (this._samples === sampleCount) {
  71184. return;
  71185. }
  71186. this._samples = sampleCount;
  71187. this._buildPipeline();
  71188. },
  71189. enumerable: true,
  71190. configurable: true
  71191. });
  71192. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  71193. get: function () {
  71194. return this._imageProcessingEnabled;
  71195. },
  71196. /**
  71197. * If image processing is enabled.
  71198. */
  71199. set: function (enabled) {
  71200. if (this._imageProcessingEnabled === enabled) {
  71201. return;
  71202. }
  71203. this._imageProcessingEnabled = enabled;
  71204. this._buildPipeline();
  71205. },
  71206. enumerable: true,
  71207. configurable: true
  71208. });
  71209. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  71210. get: function () {
  71211. return this._chromaticAberrationEnabled;
  71212. },
  71213. /**
  71214. * Enable or disable the chromaticAberration process from the pipeline
  71215. */
  71216. set: function (enabled) {
  71217. if (this._chromaticAberrationEnabled === enabled) {
  71218. return;
  71219. }
  71220. this._chromaticAberrationEnabled = enabled;
  71221. this._buildPipeline();
  71222. },
  71223. enumerable: true,
  71224. configurable: true
  71225. });
  71226. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  71227. get: function () {
  71228. return this._grainEnabled;
  71229. },
  71230. /**
  71231. * Enable or disable the grain process from the pipeline
  71232. */
  71233. set: function (enabled) {
  71234. if (this._grainEnabled === enabled) {
  71235. return;
  71236. }
  71237. this._grainEnabled = enabled;
  71238. this._buildPipeline();
  71239. },
  71240. enumerable: true,
  71241. configurable: true
  71242. });
  71243. /**
  71244. * Force the compilation of the entire pipeline.
  71245. */
  71246. DefaultRenderingPipeline.prototype.prepare = function () {
  71247. var previousState = this._buildAllowed;
  71248. this._buildAllowed = true;
  71249. this._buildPipeline();
  71250. this._buildAllowed = previousState;
  71251. };
  71252. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  71253. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  71254. if (this._hasCleared) {
  71255. postProcess.autoClear = false;
  71256. }
  71257. else {
  71258. postProcess.autoClear = true;
  71259. this._scene.autoClear = false;
  71260. this._hasCleared = true;
  71261. }
  71262. if (!skipTextureSharing) {
  71263. if (this._prevPrevPostProcess) {
  71264. postProcess.shareOutputWith(this._prevPrevPostProcess);
  71265. }
  71266. else {
  71267. postProcess.useOwnOutput();
  71268. }
  71269. if (this._prevPostProcess) {
  71270. this._prevPrevPostProcess = this._prevPostProcess;
  71271. }
  71272. this._prevPostProcess = postProcess;
  71273. }
  71274. };
  71275. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  71276. var _this = this;
  71277. if (!this._buildAllowed) {
  71278. return;
  71279. }
  71280. this._scene.autoClear = true;
  71281. var engine = this._scene.getEngine();
  71282. this._disposePostProcesses();
  71283. if (this._cameras !== null) {
  71284. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71285. // get back cameras to be used to reattach pipeline
  71286. this._cameras = this._originalCameras.slice();
  71287. }
  71288. this._reset();
  71289. this._prevPostProcess = null;
  71290. this._prevPrevPostProcess = null;
  71291. this._hasCleared = false;
  71292. if (this.depthOfFieldEnabled) {
  71293. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  71294. this.depthOfField.depthTexture = depthTexture;
  71295. if (!this.depthOfField._isReady()) {
  71296. this.depthOfField._updateEffects();
  71297. }
  71298. this.addEffect(this.depthOfField);
  71299. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  71300. }
  71301. if (this.bloomEnabled) {
  71302. if (!this.bloom._isReady()) {
  71303. this.bloom._updateEffects();
  71304. }
  71305. this.addEffect(this.bloom);
  71306. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  71307. }
  71308. if (this._imageProcessingEnabled) {
  71309. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71310. if (this._hdr) {
  71311. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71312. this._setAutoClearAndTextureSharing(this.imageProcessing);
  71313. }
  71314. else {
  71315. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71316. }
  71317. }
  71318. if (this.sharpenEnabled) {
  71319. if (!this.sharpen.isReady()) {
  71320. this.sharpen.updateEffect();
  71321. }
  71322. this.addEffect(this._sharpenEffect);
  71323. this._setAutoClearAndTextureSharing(this.sharpen);
  71324. }
  71325. if (this.grainEnabled) {
  71326. if (!this.grain.isReady()) {
  71327. this.grain.updateEffect();
  71328. }
  71329. this.addEffect(this._grainEffect);
  71330. this._setAutoClearAndTextureSharing(this.grain);
  71331. }
  71332. if (this.chromaticAberrationEnabled) {
  71333. if (!this.chromaticAberration.isReady()) {
  71334. this.chromaticAberration.updateEffect();
  71335. }
  71336. this.addEffect(this._chromaticAberrationEffect);
  71337. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71338. }
  71339. if (this.fxaaEnabled) {
  71340. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71341. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71342. this._setAutoClearAndTextureSharing(this.fxaa, true);
  71343. }
  71344. if (this._cameras !== null) {
  71345. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71346. }
  71347. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  71348. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71349. }
  71350. };
  71351. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71352. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71353. for (var i = 0; i < this._cameras.length; i++) {
  71354. var camera = this._cameras[i];
  71355. if (this.imageProcessing) {
  71356. this.imageProcessing.dispose(camera);
  71357. }
  71358. if (this.fxaa) {
  71359. this.fxaa.dispose(camera);
  71360. }
  71361. // These are created in the constructor and should not be disposed on every pipeline change
  71362. if (disposeNonRecreated) {
  71363. if (this.sharpen) {
  71364. this.sharpen.dispose(camera);
  71365. }
  71366. if (this.depthOfField) {
  71367. this.depthOfField.disposeEffects(camera);
  71368. }
  71369. if (this.bloom) {
  71370. this.bloom.disposeEffects(camera);
  71371. }
  71372. if (this.chromaticAberration) {
  71373. this.chromaticAberration.dispose(camera);
  71374. }
  71375. if (this.grain) {
  71376. this.grain.dispose(camera);
  71377. }
  71378. }
  71379. }
  71380. this.imageProcessing = null;
  71381. this.fxaa = null;
  71382. if (disposeNonRecreated) {
  71383. this.sharpen = null;
  71384. this._sharpenEffect = null;
  71385. this.depthOfField = null;
  71386. this.bloom = null;
  71387. this.chromaticAberration = null;
  71388. this._chromaticAberrationEffect = null;
  71389. this.grain = null;
  71390. this._grainEffect = null;
  71391. }
  71392. };
  71393. /**
  71394. * Dispose of the pipeline and stop all post processes
  71395. */
  71396. DefaultRenderingPipeline.prototype.dispose = function () {
  71397. this._disposePostProcesses(true);
  71398. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71399. this._scene.autoClear = true;
  71400. if (this._resizeObserver) {
  71401. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  71402. this._resizeObserver = null;
  71403. }
  71404. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  71405. _super.prototype.dispose.call(this);
  71406. };
  71407. /**
  71408. * Serialize the rendering pipeline (Used when exporting)
  71409. * @returns the serialized object
  71410. */
  71411. DefaultRenderingPipeline.prototype.serialize = function () {
  71412. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71413. serializationObject.customType = "DefaultRenderingPipeline";
  71414. return serializationObject;
  71415. };
  71416. /**
  71417. * Parse the serialized pipeline
  71418. * @param source Source pipeline.
  71419. * @param scene The scene to load the pipeline to.
  71420. * @param rootUrl The URL of the serialized pipeline.
  71421. * @returns An instantiated pipeline from the serialized object.
  71422. */
  71423. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71424. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71425. };
  71426. __decorate([
  71427. BABYLON.serialize()
  71428. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71429. __decorate([
  71430. BABYLON.serialize()
  71431. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  71432. __decorate([
  71433. BABYLON.serialize()
  71434. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71435. __decorate([
  71436. BABYLON.serialize()
  71437. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  71438. __decorate([
  71439. BABYLON.serialize()
  71440. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71441. __decorate([
  71442. BABYLON.serialize()
  71443. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71444. __decorate([
  71445. BABYLON.serialize()
  71446. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  71447. __decorate([
  71448. BABYLON.serialize()
  71449. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71450. __decorate([
  71451. BABYLON.serialize()
  71452. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71453. __decorate([
  71454. BABYLON.serialize()
  71455. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71456. __decorate([
  71457. BABYLON.serialize()
  71458. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71459. __decorate([
  71460. BABYLON.serialize()
  71461. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71462. __decorate([
  71463. BABYLON.serialize()
  71464. ], DefaultRenderingPipeline.prototype, "samples", null);
  71465. __decorate([
  71466. BABYLON.serialize()
  71467. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71468. __decorate([
  71469. BABYLON.serialize()
  71470. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71471. __decorate([
  71472. BABYLON.serialize()
  71473. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  71474. return DefaultRenderingPipeline;
  71475. }(BABYLON.PostProcessRenderPipeline));
  71476. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71477. })(BABYLON || (BABYLON = {}));
  71478. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71479. "use strict";
  71480. var BABYLON;
  71481. (function (BABYLON) {
  71482. /**
  71483. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71484. */
  71485. var GeometryBufferRenderer = /** @class */ (function () {
  71486. /**
  71487. * Creates a new G Buffer for the scene
  71488. * @param scene The scene the buffer belongs to
  71489. * @param ratio How big is the buffer related to the main canvas.
  71490. */
  71491. function GeometryBufferRenderer(scene, ratio) {
  71492. if (ratio === void 0) { ratio = 1; }
  71493. this._enablePosition = false;
  71494. this._scene = scene;
  71495. this._ratio = ratio;
  71496. // Render target
  71497. this._createRenderTargets();
  71498. }
  71499. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71500. /**
  71501. * Set the render list (meshes to be rendered) used in the G buffer.
  71502. */
  71503. set: function (meshes) {
  71504. this._multiRenderTarget.renderList = meshes;
  71505. },
  71506. enumerable: true,
  71507. configurable: true
  71508. });
  71509. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71510. /**
  71511. * Gets wether or not G buffer are supported by the running hardware.
  71512. * This requires draw buffer supports
  71513. */
  71514. get: function () {
  71515. return this._multiRenderTarget.isSupported;
  71516. },
  71517. enumerable: true,
  71518. configurable: true
  71519. });
  71520. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71521. /**
  71522. * Gets wether or not position are enabled for the G buffer.
  71523. */
  71524. get: function () {
  71525. return this._enablePosition;
  71526. },
  71527. /**
  71528. * Sets wether or not position are enabled for the G buffer.
  71529. */
  71530. set: function (enable) {
  71531. this._enablePosition = enable;
  71532. this.dispose();
  71533. this._createRenderTargets();
  71534. },
  71535. enumerable: true,
  71536. configurable: true
  71537. });
  71538. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71539. /**
  71540. * Gets the scene associated with the buffer.
  71541. */
  71542. get: function () {
  71543. return this._scene;
  71544. },
  71545. enumerable: true,
  71546. configurable: true
  71547. });
  71548. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71549. /**
  71550. * Gets the ratio used by the buffer during its creation.
  71551. * How big is the buffer related to the main canvas.
  71552. */
  71553. get: function () {
  71554. return this._ratio;
  71555. },
  71556. enumerable: true,
  71557. configurable: true
  71558. });
  71559. /**
  71560. * Checks wether everything is ready to render a submesh to the G buffer.
  71561. * @param subMesh the submesh to check readiness for
  71562. * @param useInstances is the mesh drawn using instance or not
  71563. * @returns true if ready otherwise false
  71564. */
  71565. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71566. var material = subMesh.getMaterial();
  71567. if (material && material.disableDepthWrite) {
  71568. return false;
  71569. }
  71570. var defines = [];
  71571. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71572. var mesh = subMesh.getMesh();
  71573. // Alpha test
  71574. if (material && material.needAlphaTesting()) {
  71575. defines.push("#define ALPHATEST");
  71576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71577. attribs.push(BABYLON.VertexBuffer.UVKind);
  71578. defines.push("#define UV1");
  71579. }
  71580. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71581. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71582. defines.push("#define UV2");
  71583. }
  71584. }
  71585. // Buffers
  71586. if (this._enablePosition) {
  71587. defines.push("#define POSITION");
  71588. }
  71589. // Bones
  71590. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71591. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71592. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71593. if (mesh.numBoneInfluencers > 4) {
  71594. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71595. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71596. }
  71597. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71598. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71599. }
  71600. else {
  71601. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71602. }
  71603. // Instances
  71604. if (useInstances) {
  71605. defines.push("#define INSTANCES");
  71606. attribs.push("world0");
  71607. attribs.push("world1");
  71608. attribs.push("world2");
  71609. attribs.push("world3");
  71610. }
  71611. // Get correct effect
  71612. var join = defines.join("\n");
  71613. if (this._cachedDefines !== join) {
  71614. this._cachedDefines = join;
  71615. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71616. }
  71617. return this._effect.isReady();
  71618. };
  71619. /**
  71620. * Gets the current underlying G Buffer.
  71621. * @returns the buffer
  71622. */
  71623. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71624. return this._multiRenderTarget;
  71625. };
  71626. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71627. /**
  71628. * Gets the number of samples used to render the buffer (anti aliasing).
  71629. */
  71630. get: function () {
  71631. return this._multiRenderTarget.samples;
  71632. },
  71633. /**
  71634. * Sets the number of samples used to render the buffer (anti aliasing).
  71635. */
  71636. set: function (value) {
  71637. this._multiRenderTarget.samples = value;
  71638. },
  71639. enumerable: true,
  71640. configurable: true
  71641. });
  71642. /**
  71643. * Disposes the renderer and frees up associated resources.
  71644. */
  71645. GeometryBufferRenderer.prototype.dispose = function () {
  71646. this.getGBuffer().dispose();
  71647. };
  71648. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71649. var _this = this;
  71650. var engine = this._scene.getEngine();
  71651. var count = this._enablePosition ? 3 : 2;
  71652. 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 });
  71653. if (!this.isSupported) {
  71654. return;
  71655. }
  71656. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71657. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71658. this._multiRenderTarget.refreshRate = 1;
  71659. this._multiRenderTarget.renderParticles = false;
  71660. this._multiRenderTarget.renderList = null;
  71661. // set default depth value to 1.0 (far away)
  71662. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71663. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71664. });
  71665. // Custom render function
  71666. var renderSubMesh = function (subMesh) {
  71667. var mesh = subMesh.getRenderingMesh();
  71668. var scene = _this._scene;
  71669. var engine = scene.getEngine();
  71670. var material = subMesh.getMaterial();
  71671. if (!material) {
  71672. return;
  71673. }
  71674. // Culling
  71675. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71676. // Managing instances
  71677. var batch = mesh._getInstancesRenderList(subMesh._id);
  71678. if (batch.mustReturn) {
  71679. return;
  71680. }
  71681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71682. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71683. engine.enableEffect(_this._effect);
  71684. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71685. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71686. _this._effect.setMatrix("view", scene.getViewMatrix());
  71687. // Alpha test
  71688. if (material && material.needAlphaTesting()) {
  71689. var alphaTexture = material.getAlphaTestTexture();
  71690. if (alphaTexture) {
  71691. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71692. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71693. }
  71694. }
  71695. // Bones
  71696. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71697. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71698. }
  71699. // Draw
  71700. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71701. }
  71702. };
  71703. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71704. var index;
  71705. if (depthOnlySubMeshes.length) {
  71706. engine.setColorWrite(false);
  71707. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71708. renderSubMesh(depthOnlySubMeshes.data[index]);
  71709. }
  71710. engine.setColorWrite(true);
  71711. }
  71712. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71713. renderSubMesh(opaqueSubMeshes.data[index]);
  71714. }
  71715. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71716. renderSubMesh(alphaTestSubMeshes.data[index]);
  71717. }
  71718. };
  71719. };
  71720. return GeometryBufferRenderer;
  71721. }());
  71722. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71723. })(BABYLON || (BABYLON = {}));
  71724. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71725. "use strict";
  71726. var BABYLON;
  71727. (function (BABYLON) {
  71728. var RefractionPostProcess = /** @class */ (function (_super) {
  71729. __extends(RefractionPostProcess, _super);
  71730. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71731. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71732. _this.color = color;
  71733. _this.depth = depth;
  71734. _this.colorLevel = colorLevel;
  71735. _this._ownRefractionTexture = true;
  71736. _this.onActivateObservable.add(function (cam) {
  71737. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71738. });
  71739. _this.onApplyObservable.add(function (effect) {
  71740. effect.setColor3("baseColor", _this.color);
  71741. effect.setFloat("depth", _this.depth);
  71742. effect.setFloat("colorLevel", _this.colorLevel);
  71743. effect.setTexture("refractionSampler", _this._refTexture);
  71744. });
  71745. return _this;
  71746. }
  71747. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71748. /**
  71749. * Gets or sets the refraction texture
  71750. * Please note that you are responsible for disposing the texture if you set it manually
  71751. */
  71752. get: function () {
  71753. return this._refTexture;
  71754. },
  71755. set: function (value) {
  71756. if (this._refTexture && this._ownRefractionTexture) {
  71757. this._refTexture.dispose();
  71758. }
  71759. this._refTexture = value;
  71760. this._ownRefractionTexture = false;
  71761. },
  71762. enumerable: true,
  71763. configurable: true
  71764. });
  71765. // Methods
  71766. RefractionPostProcess.prototype.dispose = function (camera) {
  71767. if (this._refTexture && this._ownRefractionTexture) {
  71768. this._refTexture.dispose();
  71769. this._refTexture = null;
  71770. }
  71771. _super.prototype.dispose.call(this, camera);
  71772. };
  71773. return RefractionPostProcess;
  71774. }(BABYLON.PostProcess));
  71775. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71776. })(BABYLON || (BABYLON = {}));
  71777. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71778. "use strict";
  71779. var BABYLON;
  71780. (function (BABYLON) {
  71781. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71782. __extends(BlackAndWhitePostProcess, _super);
  71783. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71784. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71785. _this.degree = 1;
  71786. _this.onApplyObservable.add(function (effect) {
  71787. effect.setFloat("degree", _this.degree);
  71788. });
  71789. return _this;
  71790. }
  71791. return BlackAndWhitePostProcess;
  71792. }(BABYLON.PostProcess));
  71793. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71794. })(BABYLON || (BABYLON = {}));
  71795. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71796. "use strict";
  71797. var BABYLON;
  71798. (function (BABYLON) {
  71799. /**
  71800. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71801. * input texture to perform effects such as edge detection or sharpening
  71802. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71803. */
  71804. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71805. __extends(ConvolutionPostProcess, _super);
  71806. /**
  71807. * Creates a new instance ConvolutionPostProcess
  71808. * @param name The name of the effect.
  71809. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71810. * @param options The required width/height ratio to downsize to before computing the render pass.
  71811. * @param camera The camera to apply the render pass to.
  71812. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71813. * @param engine The engine which the post process will be applied. (default: current engine)
  71814. * @param reusable If the post process can be reused on the same frame. (default: false)
  71815. * @param textureType Type of textures used when performing the post process. (default: 0)
  71816. */
  71817. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71818. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71819. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71820. _this.kernel = kernel;
  71821. _this.onApply = function (effect) {
  71822. effect.setFloat2("screenSize", _this.width, _this.height);
  71823. effect.setArray("kernel", _this.kernel);
  71824. };
  71825. return _this;
  71826. }
  71827. // Statics
  71828. /**
  71829. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71830. */
  71831. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71832. /**
  71833. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71834. */
  71835. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71836. /**
  71837. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71838. */
  71839. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71840. /**
  71841. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71842. */
  71843. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71844. /**
  71845. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71846. */
  71847. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71848. /**
  71849. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71850. */
  71851. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71852. return ConvolutionPostProcess;
  71853. }(BABYLON.PostProcess));
  71854. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71855. })(BABYLON || (BABYLON = {}));
  71856. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71857. "use strict";
  71858. var BABYLON;
  71859. (function (BABYLON) {
  71860. var FilterPostProcess = /** @class */ (function (_super) {
  71861. __extends(FilterPostProcess, _super);
  71862. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71863. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71864. _this.kernelMatrix = kernelMatrix;
  71865. _this.onApply = function (effect) {
  71866. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71867. };
  71868. return _this;
  71869. }
  71870. return FilterPostProcess;
  71871. }(BABYLON.PostProcess));
  71872. BABYLON.FilterPostProcess = FilterPostProcess;
  71873. })(BABYLON || (BABYLON = {}));
  71874. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71875. "use strict";
  71876. var BABYLON;
  71877. (function (BABYLON) {
  71878. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71879. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71880. __extends(VolumetricLightScatteringPostProcess, _super);
  71881. /**
  71882. * @constructor
  71883. * @param {string} name - The post-process name
  71884. * @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)
  71885. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71886. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71887. * @param {number} samples - The post-process quality, default 100
  71888. * @param {number} samplingMode - The post-process filtering mode
  71889. * @param {BABYLON.Engine} engine - The babylon engine
  71890. * @param {boolean} reusable - If the post-process is reusable
  71891. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71892. */
  71893. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71894. if (samples === void 0) { samples = 100; }
  71895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71896. 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;
  71897. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71898. /**
  71899. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71900. * @type {Vector3}
  71901. */
  71902. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71903. /**
  71904. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71905. * @type {boolean}
  71906. */
  71907. _this.useCustomMeshPosition = false;
  71908. /**
  71909. * If the post-process should inverse the light scattering direction
  71910. * @type {boolean}
  71911. */
  71912. _this.invert = true;
  71913. /**
  71914. * Array containing the excluded meshes not rendered in the internal pass
  71915. */
  71916. _this.excludedMeshes = new Array();
  71917. /**
  71918. * Controls the overall intensity of the post-process
  71919. * @type {number}
  71920. */
  71921. _this.exposure = 0.3;
  71922. /**
  71923. * Dissipates each sample's contribution in range [0, 1]
  71924. * @type {number}
  71925. */
  71926. _this.decay = 0.96815;
  71927. /**
  71928. * Controls the overall intensity of each sample
  71929. * @type {number}
  71930. */
  71931. _this.weight = 0.58767;
  71932. /**
  71933. * Controls the density of each sample
  71934. * @type {number}
  71935. */
  71936. _this.density = 0.926;
  71937. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71938. engine = scene.getEngine();
  71939. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71940. // Configure mesh
  71941. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71942. // Configure
  71943. _this._createPass(scene, ratio.passRatio || ratio);
  71944. _this.onActivate = function (camera) {
  71945. if (!_this.isSupported) {
  71946. _this.dispose(camera);
  71947. }
  71948. _this.onActivate = null;
  71949. };
  71950. _this.onApplyObservable.add(function (effect) {
  71951. _this._updateMeshScreenCoordinates(scene);
  71952. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71953. effect.setFloat("exposure", _this.exposure);
  71954. effect.setFloat("decay", _this.decay);
  71955. effect.setFloat("weight", _this.weight);
  71956. effect.setFloat("density", _this.density);
  71957. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71958. });
  71959. return _this;
  71960. }
  71961. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71962. get: function () {
  71963. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71964. return false;
  71965. },
  71966. set: function (useDiffuseColor) {
  71967. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71968. },
  71969. enumerable: true,
  71970. configurable: true
  71971. });
  71972. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71973. return "VolumetricLightScatteringPostProcess";
  71974. };
  71975. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71976. var mesh = subMesh.getMesh();
  71977. // Render this.mesh as default
  71978. if (mesh === this.mesh && mesh.material) {
  71979. return mesh.material.isReady(mesh);
  71980. }
  71981. var defines = [];
  71982. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71983. var material = subMesh.getMaterial();
  71984. // Alpha test
  71985. if (material) {
  71986. if (material.needAlphaTesting()) {
  71987. defines.push("#define ALPHATEST");
  71988. }
  71989. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71990. attribs.push(BABYLON.VertexBuffer.UVKind);
  71991. defines.push("#define UV1");
  71992. }
  71993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71994. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71995. defines.push("#define UV2");
  71996. }
  71997. }
  71998. // Bones
  71999. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72002. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72003. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72004. }
  72005. else {
  72006. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72007. }
  72008. // Instances
  72009. if (useInstances) {
  72010. defines.push("#define INSTANCES");
  72011. attribs.push("world0");
  72012. attribs.push("world1");
  72013. attribs.push("world2");
  72014. attribs.push("world3");
  72015. }
  72016. // Get correct effect
  72017. var join = defines.join("\n");
  72018. if (this._cachedDefines !== join) {
  72019. this._cachedDefines = join;
  72020. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  72021. }
  72022. return this._volumetricLightScatteringPass.isReady();
  72023. };
  72024. /**
  72025. * Sets the new light position for light scattering effect
  72026. * @param {BABYLON.Vector3} The new custom light position
  72027. */
  72028. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  72029. this.customMeshPosition = position;
  72030. };
  72031. /**
  72032. * Returns the light position for light scattering effect
  72033. * @return {BABYLON.Vector3} The custom light position
  72034. */
  72035. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  72036. return this.customMeshPosition;
  72037. };
  72038. /**
  72039. * Disposes the internal assets and detaches the post-process from the camera
  72040. */
  72041. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  72042. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  72043. if (rttIndex !== -1) {
  72044. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  72045. }
  72046. this._volumetricLightScatteringRTT.dispose();
  72047. _super.prototype.dispose.call(this, camera);
  72048. };
  72049. /**
  72050. * Returns the render target texture used by the post-process
  72051. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  72052. */
  72053. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  72054. return this._volumetricLightScatteringRTT;
  72055. };
  72056. // Private methods
  72057. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  72058. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  72059. return true;
  72060. }
  72061. return false;
  72062. };
  72063. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  72064. var _this = this;
  72065. var engine = scene.getEngine();
  72066. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72067. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72068. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72069. this._volumetricLightScatteringRTT.renderList = null;
  72070. this._volumetricLightScatteringRTT.renderParticles = false;
  72071. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  72072. var camera = this.getCamera();
  72073. if (camera) {
  72074. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72075. }
  72076. else {
  72077. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72078. }
  72079. // Custom render function for submeshes
  72080. var renderSubMesh = function (subMesh) {
  72081. var mesh = subMesh.getRenderingMesh();
  72082. if (_this._meshExcluded(mesh)) {
  72083. return;
  72084. }
  72085. var material = subMesh.getMaterial();
  72086. if (!material) {
  72087. return;
  72088. }
  72089. var scene = mesh.getScene();
  72090. var engine = scene.getEngine();
  72091. // Culling
  72092. engine.setState(material.backFaceCulling);
  72093. // Managing instances
  72094. var batch = mesh._getInstancesRenderList(subMesh._id);
  72095. if (batch.mustReturn) {
  72096. return;
  72097. }
  72098. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72099. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  72100. var effect = _this._volumetricLightScatteringPass;
  72101. if (mesh === _this.mesh) {
  72102. if (subMesh.effect) {
  72103. effect = subMesh.effect;
  72104. }
  72105. else {
  72106. effect = material.getEffect();
  72107. }
  72108. }
  72109. engine.enableEffect(effect);
  72110. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  72111. if (mesh === _this.mesh) {
  72112. material.bind(mesh.getWorldMatrix(), mesh);
  72113. }
  72114. else {
  72115. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  72116. // Alpha test
  72117. if (material && material.needAlphaTesting()) {
  72118. var alphaTexture = material.getAlphaTestTexture();
  72119. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  72120. if (alphaTexture) {
  72121. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72122. }
  72123. }
  72124. // Bones
  72125. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72126. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72127. }
  72128. }
  72129. // Draw
  72130. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  72131. }
  72132. };
  72133. // Render target texture callbacks
  72134. var savedSceneClearColor;
  72135. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  72136. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  72137. savedSceneClearColor = scene.clearColor;
  72138. scene.clearColor = sceneClearColor;
  72139. });
  72140. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  72141. scene.clearColor = savedSceneClearColor;
  72142. });
  72143. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72144. var engine = scene.getEngine();
  72145. var index;
  72146. if (depthOnlySubMeshes.length) {
  72147. engine.setColorWrite(false);
  72148. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72149. renderSubMesh(depthOnlySubMeshes.data[index]);
  72150. }
  72151. engine.setColorWrite(true);
  72152. }
  72153. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72154. renderSubMesh(opaqueSubMeshes.data[index]);
  72155. }
  72156. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72157. renderSubMesh(alphaTestSubMeshes.data[index]);
  72158. }
  72159. if (transparentSubMeshes.length) {
  72160. // Sort sub meshes
  72161. for (index = 0; index < transparentSubMeshes.length; index++) {
  72162. var submesh = transparentSubMeshes.data[index];
  72163. var boundingInfo = submesh.getBoundingInfo();
  72164. if (boundingInfo && scene.activeCamera) {
  72165. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  72166. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  72167. }
  72168. }
  72169. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  72170. sortedArray.sort(function (a, b) {
  72171. // Alpha index first
  72172. if (a._alphaIndex > b._alphaIndex) {
  72173. return 1;
  72174. }
  72175. if (a._alphaIndex < b._alphaIndex) {
  72176. return -1;
  72177. }
  72178. // Then distance to camera
  72179. if (a._distanceToCamera < b._distanceToCamera) {
  72180. return 1;
  72181. }
  72182. if (a._distanceToCamera > b._distanceToCamera) {
  72183. return -1;
  72184. }
  72185. return 0;
  72186. });
  72187. // Render sub meshes
  72188. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  72189. for (index = 0; index < sortedArray.length; index++) {
  72190. renderSubMesh(sortedArray[index]);
  72191. }
  72192. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72193. }
  72194. };
  72195. };
  72196. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  72197. var transform = scene.getTransformMatrix();
  72198. var meshPosition;
  72199. if (this.useCustomMeshPosition) {
  72200. meshPosition = this.customMeshPosition;
  72201. }
  72202. else if (this.attachedNode) {
  72203. meshPosition = this.attachedNode.position;
  72204. }
  72205. else {
  72206. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  72207. }
  72208. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  72209. this._screenCoordinates.x = pos.x / this._viewPort.width;
  72210. this._screenCoordinates.y = pos.y / this._viewPort.height;
  72211. if (this.invert)
  72212. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  72213. };
  72214. // Static methods
  72215. /**
  72216. * Creates a default mesh for the Volumeric Light Scattering post-process
  72217. * @param {string} The mesh name
  72218. * @param {BABYLON.Scene} The scene where to create the mesh
  72219. * @return {BABYLON.Mesh} the default mesh
  72220. */
  72221. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  72222. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  72223. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  72224. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  72225. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  72226. mesh.material = material;
  72227. return mesh;
  72228. };
  72229. __decorate([
  72230. BABYLON.serializeAsVector3()
  72231. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  72232. __decorate([
  72233. BABYLON.serialize()
  72234. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  72235. __decorate([
  72236. BABYLON.serialize()
  72237. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  72238. __decorate([
  72239. BABYLON.serializeAsMeshReference()
  72240. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  72241. __decorate([
  72242. BABYLON.serialize()
  72243. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  72244. __decorate([
  72245. BABYLON.serialize()
  72246. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  72247. __decorate([
  72248. BABYLON.serialize()
  72249. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  72250. __decorate([
  72251. BABYLON.serialize()
  72252. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  72253. __decorate([
  72254. BABYLON.serialize()
  72255. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  72256. return VolumetricLightScatteringPostProcess;
  72257. }(BABYLON.PostProcess));
  72258. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  72259. })(BABYLON || (BABYLON = {}));
  72260. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  72261. "use strict";
  72262. //
  72263. // This post-process allows the modification of rendered colors by using
  72264. // a 'look-up table' (LUT). This effect is also called Color Grading.
  72265. //
  72266. // The object needs to be provided an url to a texture containing the color
  72267. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  72268. // Use an image editing software to tweak the LUT to match your needs.
  72269. //
  72270. // For an example of a color LUT, see here:
  72271. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  72272. // For explanations on color grading, see here:
  72273. // http://udn.epicgames.com/Three/ColorGrading.html
  72274. //
  72275. var BABYLON;
  72276. (function (BABYLON) {
  72277. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  72278. __extends(ColorCorrectionPostProcess, _super);
  72279. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  72280. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  72281. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72282. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  72283. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72284. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72285. _this.onApply = function (effect) {
  72286. effect.setTexture("colorTable", _this._colorTableTexture);
  72287. };
  72288. return _this;
  72289. }
  72290. return ColorCorrectionPostProcess;
  72291. }(BABYLON.PostProcess));
  72292. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72293. })(BABYLON || (BABYLON = {}));
  72294. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72295. "use strict";
  72296. var BABYLON;
  72297. (function (BABYLON) {
  72298. var TonemappingOperator;
  72299. (function (TonemappingOperator) {
  72300. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72301. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72302. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72303. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72304. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72305. ;
  72306. var TonemapPostProcess = /** @class */ (function (_super) {
  72307. __extends(TonemapPostProcess, _super);
  72308. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72310. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72311. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72312. _this._operator = _operator;
  72313. _this.exposureAdjustment = exposureAdjustment;
  72314. var defines = "#define ";
  72315. if (_this._operator === TonemappingOperator.Hable)
  72316. defines += "HABLE_TONEMAPPING";
  72317. else if (_this._operator === TonemappingOperator.Reinhard)
  72318. defines += "REINHARD_TONEMAPPING";
  72319. else if (_this._operator === TonemappingOperator.HejiDawson)
  72320. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72321. else if (_this._operator === TonemappingOperator.Photographic)
  72322. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72323. //sadly a second call to create the effect.
  72324. _this.updateEffect(defines);
  72325. _this.onApply = function (effect) {
  72326. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72327. };
  72328. return _this;
  72329. }
  72330. return TonemapPostProcess;
  72331. }(BABYLON.PostProcess));
  72332. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72333. })(BABYLON || (BABYLON = {}));
  72334. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72335. "use strict";
  72336. var BABYLON;
  72337. (function (BABYLON) {
  72338. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72339. __extends(DisplayPassPostProcess, _super);
  72340. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72341. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72342. }
  72343. return DisplayPassPostProcess;
  72344. }(BABYLON.PostProcess));
  72345. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72346. })(BABYLON || (BABYLON = {}));
  72347. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72348. "use strict";
  72349. var BABYLON;
  72350. (function (BABYLON) {
  72351. var HighlightsPostProcess = /** @class */ (function (_super) {
  72352. __extends(HighlightsPostProcess, _super);
  72353. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72354. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72355. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72356. }
  72357. return HighlightsPostProcess;
  72358. }(BABYLON.PostProcess));
  72359. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72360. })(BABYLON || (BABYLON = {}));
  72361. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72362. "use strict";
  72363. var BABYLON;
  72364. (function (BABYLON) {
  72365. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72366. __extends(ImageProcessingPostProcess, _super);
  72367. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72368. if (camera === void 0) { camera = null; }
  72369. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72370. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72371. _this._fromLinearSpace = true;
  72372. /**
  72373. * Defines cache preventing GC.
  72374. */
  72375. _this._defines = {
  72376. IMAGEPROCESSING: false,
  72377. VIGNETTE: false,
  72378. VIGNETTEBLENDMODEMULTIPLY: false,
  72379. VIGNETTEBLENDMODEOPAQUE: false,
  72380. TONEMAPPING: false,
  72381. CONTRAST: false,
  72382. COLORCURVES: false,
  72383. COLORGRADING: false,
  72384. COLORGRADING3D: false,
  72385. FROMLINEARSPACE: false,
  72386. SAMPLER3DGREENDEPTH: false,
  72387. SAMPLER3DBGRMAP: false,
  72388. IMAGEPROCESSINGPOSTPROCESS: false,
  72389. EXPOSURE: false,
  72390. };
  72391. // Setup the configuration as forced by the constructor. This would then not force the
  72392. // scene materials output in linear space and let untouched the default forward pass.
  72393. if (imageProcessingConfiguration) {
  72394. imageProcessingConfiguration.applyByPostProcess = true;
  72395. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72396. // This will cause the shader to be compiled
  72397. _this.fromLinearSpace = false;
  72398. }
  72399. else {
  72400. _this._attachImageProcessingConfiguration(null, true);
  72401. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72402. }
  72403. _this.onApply = function (effect) {
  72404. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72405. };
  72406. return _this;
  72407. }
  72408. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72409. /**
  72410. * Gets the image processing configuration used either in this material.
  72411. */
  72412. get: function () {
  72413. return this._imageProcessingConfiguration;
  72414. },
  72415. /**
  72416. * Sets the Default image processing configuration used either in the this material.
  72417. *
  72418. * If sets to null, the scene one is in use.
  72419. */
  72420. set: function (value) {
  72421. this._attachImageProcessingConfiguration(value);
  72422. },
  72423. enumerable: true,
  72424. configurable: true
  72425. });
  72426. /**
  72427. * Attaches a new image processing configuration to the PBR Material.
  72428. * @param configuration
  72429. */
  72430. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72431. var _this = this;
  72432. if (doNotBuild === void 0) { doNotBuild = false; }
  72433. if (configuration === this._imageProcessingConfiguration) {
  72434. return;
  72435. }
  72436. // Detaches observer.
  72437. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72438. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72439. }
  72440. // Pick the scene configuration if needed.
  72441. if (!configuration) {
  72442. var scene = null;
  72443. var engine = this.getEngine();
  72444. var camera = this.getCamera();
  72445. if (camera) {
  72446. scene = camera.getScene();
  72447. }
  72448. else if (engine && engine.scenes) {
  72449. var scenes = engine.scenes;
  72450. scene = scenes[scenes.length - 1];
  72451. }
  72452. else {
  72453. scene = BABYLON.Engine.LastCreatedScene;
  72454. }
  72455. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72456. }
  72457. else {
  72458. this._imageProcessingConfiguration = configuration;
  72459. }
  72460. // Attaches observer.
  72461. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72462. _this._updateParameters();
  72463. });
  72464. // Ensure the effect will be rebuilt.
  72465. if (!doNotBuild) {
  72466. this._updateParameters();
  72467. }
  72468. };
  72469. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72470. /**
  72471. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72472. */
  72473. get: function () {
  72474. return this.imageProcessingConfiguration.colorCurves;
  72475. },
  72476. /**
  72477. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72478. */
  72479. set: function (value) {
  72480. this.imageProcessingConfiguration.colorCurves = value;
  72481. },
  72482. enumerable: true,
  72483. configurable: true
  72484. });
  72485. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72486. /**
  72487. * Gets wether the color curves effect is enabled.
  72488. */
  72489. get: function () {
  72490. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72491. },
  72492. /**
  72493. * Sets wether the color curves effect is enabled.
  72494. */
  72495. set: function (value) {
  72496. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72497. },
  72498. enumerable: true,
  72499. configurable: true
  72500. });
  72501. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72502. /**
  72503. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72504. */
  72505. get: function () {
  72506. return this.imageProcessingConfiguration.colorGradingTexture;
  72507. },
  72508. /**
  72509. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72510. */
  72511. set: function (value) {
  72512. this.imageProcessingConfiguration.colorGradingTexture = value;
  72513. },
  72514. enumerable: true,
  72515. configurable: true
  72516. });
  72517. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72518. /**
  72519. * Gets wether the color grading effect is enabled.
  72520. */
  72521. get: function () {
  72522. return this.imageProcessingConfiguration.colorGradingEnabled;
  72523. },
  72524. /**
  72525. * Gets wether the color grading effect is enabled.
  72526. */
  72527. set: function (value) {
  72528. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72529. },
  72530. enumerable: true,
  72531. configurable: true
  72532. });
  72533. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72534. /**
  72535. * Gets exposure used in the effect.
  72536. */
  72537. get: function () {
  72538. return this.imageProcessingConfiguration.exposure;
  72539. },
  72540. /**
  72541. * Sets exposure used in the effect.
  72542. */
  72543. set: function (value) {
  72544. this.imageProcessingConfiguration.exposure = value;
  72545. },
  72546. enumerable: true,
  72547. configurable: true
  72548. });
  72549. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72550. /**
  72551. * Gets wether tonemapping is enabled or not.
  72552. */
  72553. get: function () {
  72554. return this._imageProcessingConfiguration.toneMappingEnabled;
  72555. },
  72556. /**
  72557. * Sets wether tonemapping is enabled or not
  72558. */
  72559. set: function (value) {
  72560. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72561. },
  72562. enumerable: true,
  72563. configurable: true
  72564. });
  72565. ;
  72566. ;
  72567. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72568. /**
  72569. * Gets contrast used in the effect.
  72570. */
  72571. get: function () {
  72572. return this.imageProcessingConfiguration.contrast;
  72573. },
  72574. /**
  72575. * Sets contrast used in the effect.
  72576. */
  72577. set: function (value) {
  72578. this.imageProcessingConfiguration.contrast = value;
  72579. },
  72580. enumerable: true,
  72581. configurable: true
  72582. });
  72583. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72584. /**
  72585. * Gets Vignette stretch size.
  72586. */
  72587. get: function () {
  72588. return this.imageProcessingConfiguration.vignetteStretch;
  72589. },
  72590. /**
  72591. * Sets Vignette stretch size.
  72592. */
  72593. set: function (value) {
  72594. this.imageProcessingConfiguration.vignetteStretch = value;
  72595. },
  72596. enumerable: true,
  72597. configurable: true
  72598. });
  72599. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72600. /**
  72601. * Gets Vignette centre X Offset.
  72602. */
  72603. get: function () {
  72604. return this.imageProcessingConfiguration.vignetteCentreX;
  72605. },
  72606. /**
  72607. * Sets Vignette centre X Offset.
  72608. */
  72609. set: function (value) {
  72610. this.imageProcessingConfiguration.vignetteCentreX = value;
  72611. },
  72612. enumerable: true,
  72613. configurable: true
  72614. });
  72615. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72616. /**
  72617. * Gets Vignette centre Y Offset.
  72618. */
  72619. get: function () {
  72620. return this.imageProcessingConfiguration.vignetteCentreY;
  72621. },
  72622. /**
  72623. * Sets Vignette centre Y Offset.
  72624. */
  72625. set: function (value) {
  72626. this.imageProcessingConfiguration.vignetteCentreY = value;
  72627. },
  72628. enumerable: true,
  72629. configurable: true
  72630. });
  72631. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72632. /**
  72633. * Gets Vignette weight or intensity of the vignette effect.
  72634. */
  72635. get: function () {
  72636. return this.imageProcessingConfiguration.vignetteWeight;
  72637. },
  72638. /**
  72639. * Sets Vignette weight or intensity of the vignette effect.
  72640. */
  72641. set: function (value) {
  72642. this.imageProcessingConfiguration.vignetteWeight = value;
  72643. },
  72644. enumerable: true,
  72645. configurable: true
  72646. });
  72647. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72648. /**
  72649. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72650. * if vignetteEnabled is set to true.
  72651. */
  72652. get: function () {
  72653. return this.imageProcessingConfiguration.vignetteColor;
  72654. },
  72655. /**
  72656. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72657. * if vignetteEnabled is set to true.
  72658. */
  72659. set: function (value) {
  72660. this.imageProcessingConfiguration.vignetteColor = value;
  72661. },
  72662. enumerable: true,
  72663. configurable: true
  72664. });
  72665. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72666. /**
  72667. * Gets Camera field of view used by the Vignette effect.
  72668. */
  72669. get: function () {
  72670. return this.imageProcessingConfiguration.vignetteCameraFov;
  72671. },
  72672. /**
  72673. * Sets Camera field of view used by the Vignette effect.
  72674. */
  72675. set: function (value) {
  72676. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72677. },
  72678. enumerable: true,
  72679. configurable: true
  72680. });
  72681. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72682. /**
  72683. * Gets the vignette blend mode allowing different kind of effect.
  72684. */
  72685. get: function () {
  72686. return this.imageProcessingConfiguration.vignetteBlendMode;
  72687. },
  72688. /**
  72689. * Sets the vignette blend mode allowing different kind of effect.
  72690. */
  72691. set: function (value) {
  72692. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72693. },
  72694. enumerable: true,
  72695. configurable: true
  72696. });
  72697. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72698. /**
  72699. * Gets wether the vignette effect is enabled.
  72700. */
  72701. get: function () {
  72702. return this.imageProcessingConfiguration.vignetteEnabled;
  72703. },
  72704. /**
  72705. * Sets wether the vignette effect is enabled.
  72706. */
  72707. set: function (value) {
  72708. this.imageProcessingConfiguration.vignetteEnabled = value;
  72709. },
  72710. enumerable: true,
  72711. configurable: true
  72712. });
  72713. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72714. /**
  72715. * Gets wether the input of the processing is in Gamma or Linear Space.
  72716. */
  72717. get: function () {
  72718. return this._fromLinearSpace;
  72719. },
  72720. /**
  72721. * Sets wether the input of the processing is in Gamma or Linear Space.
  72722. */
  72723. set: function (value) {
  72724. if (this._fromLinearSpace === value) {
  72725. return;
  72726. }
  72727. this._fromLinearSpace = value;
  72728. this._updateParameters();
  72729. },
  72730. enumerable: true,
  72731. configurable: true
  72732. });
  72733. ImageProcessingPostProcess.prototype.getClassName = function () {
  72734. return "ImageProcessingPostProcess";
  72735. };
  72736. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72737. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72738. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72739. var defines = "";
  72740. for (var define in this._defines) {
  72741. if (this._defines[define]) {
  72742. defines += "#define " + define + ";\r\n";
  72743. }
  72744. }
  72745. var samplers = ["textureSampler"];
  72746. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72747. var uniforms = ["scale"];
  72748. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72749. this.updateEffect(defines, uniforms, samplers);
  72750. };
  72751. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72752. _super.prototype.dispose.call(this, camera);
  72753. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72754. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72755. }
  72756. this.imageProcessingConfiguration.applyByPostProcess = false;
  72757. };
  72758. __decorate([
  72759. BABYLON.serialize()
  72760. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72761. return ImageProcessingPostProcess;
  72762. }(BABYLON.PostProcess));
  72763. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72764. })(BABYLON || (BABYLON = {}));
  72765. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72766. "use strict";
  72767. var BABYLON;
  72768. (function (BABYLON) {
  72769. var Bone = /** @class */ (function (_super) {
  72770. __extends(Bone, _super);
  72771. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72772. if (parentBone === void 0) { parentBone = null; }
  72773. if (localMatrix === void 0) { localMatrix = null; }
  72774. if (restPose === void 0) { restPose = null; }
  72775. if (baseMatrix === void 0) { baseMatrix = null; }
  72776. if (index === void 0) { index = null; }
  72777. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72778. _this.name = name;
  72779. _this.children = new Array();
  72780. _this.animations = new Array();
  72781. // Set this value to map this bone to a different index in the transform matrices.
  72782. // Set this value to -1 to exclude the bone from the transform matrices.
  72783. _this._index = null;
  72784. _this._worldTransform = new BABYLON.Matrix();
  72785. _this._absoluteTransform = new BABYLON.Matrix();
  72786. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72787. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72788. _this._scaleVector = BABYLON.Vector3.One();
  72789. _this._negateScaleChildren = BABYLON.Vector3.One();
  72790. _this._scalingDeterminant = 1;
  72791. _this._skeleton = skeleton;
  72792. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72793. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72794. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72795. _this._index = index;
  72796. skeleton.bones.push(_this);
  72797. _this.setParent(parentBone, false);
  72798. _this._updateDifferenceMatrix();
  72799. return _this;
  72800. }
  72801. Object.defineProperty(Bone.prototype, "_matrix", {
  72802. get: function () {
  72803. return this._localMatrix;
  72804. },
  72805. set: function (val) {
  72806. if (this._localMatrix) {
  72807. this._localMatrix.copyFrom(val);
  72808. }
  72809. else {
  72810. this._localMatrix = val;
  72811. }
  72812. },
  72813. enumerable: true,
  72814. configurable: true
  72815. });
  72816. // Members
  72817. Bone.prototype.getSkeleton = function () {
  72818. return this._skeleton;
  72819. };
  72820. Bone.prototype.getParent = function () {
  72821. return this._parent;
  72822. };
  72823. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72824. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72825. if (this._parent === parent) {
  72826. return;
  72827. }
  72828. if (this._parent) {
  72829. var index = this._parent.children.indexOf(this);
  72830. if (index !== -1) {
  72831. this._parent.children.splice(index, 1);
  72832. }
  72833. }
  72834. this._parent = parent;
  72835. if (this._parent) {
  72836. this._parent.children.push(this);
  72837. }
  72838. if (updateDifferenceMatrix) {
  72839. this._updateDifferenceMatrix();
  72840. }
  72841. };
  72842. Bone.prototype.getLocalMatrix = function () {
  72843. return this._localMatrix;
  72844. };
  72845. Bone.prototype.getBaseMatrix = function () {
  72846. return this._baseMatrix;
  72847. };
  72848. Bone.prototype.getRestPose = function () {
  72849. return this._restPose;
  72850. };
  72851. Bone.prototype.returnToRest = function () {
  72852. this.updateMatrix(this._restPose.clone());
  72853. };
  72854. Bone.prototype.getWorldMatrix = function () {
  72855. return this._worldTransform;
  72856. };
  72857. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72858. return this._invertedAbsoluteTransform;
  72859. };
  72860. Bone.prototype.getAbsoluteTransform = function () {
  72861. return this._absoluteTransform;
  72862. };
  72863. Object.defineProperty(Bone.prototype, "position", {
  72864. // Properties (matches AbstractMesh properties)
  72865. get: function () {
  72866. return this.getPosition();
  72867. },
  72868. set: function (newPosition) {
  72869. this.setPosition(newPosition);
  72870. },
  72871. enumerable: true,
  72872. configurable: true
  72873. });
  72874. Object.defineProperty(Bone.prototype, "rotation", {
  72875. get: function () {
  72876. return this.getRotation();
  72877. },
  72878. set: function (newRotation) {
  72879. this.setRotation(newRotation);
  72880. },
  72881. enumerable: true,
  72882. configurable: true
  72883. });
  72884. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72885. get: function () {
  72886. return this.getRotationQuaternion();
  72887. },
  72888. set: function (newRotation) {
  72889. this.setRotationQuaternion(newRotation);
  72890. },
  72891. enumerable: true,
  72892. configurable: true
  72893. });
  72894. Object.defineProperty(Bone.prototype, "scaling", {
  72895. get: function () {
  72896. return this.getScale();
  72897. },
  72898. set: function (newScaling) {
  72899. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72900. },
  72901. enumerable: true,
  72902. configurable: true
  72903. });
  72904. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72905. /**
  72906. * Gets the animation properties override
  72907. */
  72908. get: function () {
  72909. return this._skeleton.animationPropertiesOverride;
  72910. },
  72911. enumerable: true,
  72912. configurable: true
  72913. });
  72914. // Methods
  72915. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72916. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72917. this._baseMatrix = matrix.clone();
  72918. this._localMatrix = matrix.clone();
  72919. this._skeleton._markAsDirty();
  72920. if (updateDifferenceMatrix) {
  72921. this._updateDifferenceMatrix();
  72922. }
  72923. };
  72924. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72925. if (!rootMatrix) {
  72926. rootMatrix = this._baseMatrix;
  72927. }
  72928. if (this._parent) {
  72929. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72930. }
  72931. else {
  72932. this._absoluteTransform.copyFrom(rootMatrix);
  72933. }
  72934. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72935. for (var index = 0; index < this.children.length; index++) {
  72936. this.children[index]._updateDifferenceMatrix();
  72937. }
  72938. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72939. };
  72940. Bone.prototype.markAsDirty = function () {
  72941. this._currentRenderId++;
  72942. this._childRenderId++;
  72943. this._skeleton._markAsDirty();
  72944. };
  72945. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72946. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72947. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72948. // all animation may be coming from a library skeleton, so may need to create animation
  72949. if (this.animations.length === 0) {
  72950. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72951. this.animations[0].setKeys([]);
  72952. }
  72953. // get animation info / verify there is such a range from the source bone
  72954. var sourceRange = source.animations[0].getRange(rangeName);
  72955. if (!sourceRange) {
  72956. return false;
  72957. }
  72958. var from = sourceRange.from;
  72959. var to = sourceRange.to;
  72960. var sourceKeys = source.animations[0].getKeys();
  72961. // rescaling prep
  72962. var sourceBoneLength = source.length;
  72963. var sourceParent = source.getParent();
  72964. var parent = this.getParent();
  72965. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72966. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72967. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72968. var destKeys = this.animations[0].getKeys();
  72969. // loop vars declaration
  72970. var orig;
  72971. var origTranslation;
  72972. var mat;
  72973. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72974. orig = sourceKeys[key];
  72975. if (orig.frame >= from && orig.frame <= to) {
  72976. if (rescaleAsRequired) {
  72977. mat = orig.value.clone();
  72978. // scale based on parent ratio, when bone has parent
  72979. if (parentScalingReqd) {
  72980. origTranslation = mat.getTranslation();
  72981. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72982. // scale based on skeleton dimension ratio when root bone, and value is passed
  72983. }
  72984. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72985. origTranslation = mat.getTranslation();
  72986. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72987. // use original when root bone, and no data for skelDimensionsRatio
  72988. }
  72989. else {
  72990. mat = orig.value;
  72991. }
  72992. }
  72993. else {
  72994. mat = orig.value;
  72995. }
  72996. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72997. }
  72998. }
  72999. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  73000. return true;
  73001. };
  73002. /**
  73003. * Translate the bone in local or world space.
  73004. * @param vec The amount to translate the bone.
  73005. * @param space The space that the translation is in.
  73006. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73007. */
  73008. Bone.prototype.translate = function (vec, space, mesh) {
  73009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73010. var lm = this.getLocalMatrix();
  73011. if (space == BABYLON.Space.LOCAL) {
  73012. lm.m[12] += vec.x;
  73013. lm.m[13] += vec.y;
  73014. lm.m[14] += vec.z;
  73015. }
  73016. else {
  73017. var wm = null;
  73018. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73019. if (mesh) {
  73020. wm = mesh.getWorldMatrix();
  73021. }
  73022. this._skeleton.computeAbsoluteTransforms();
  73023. var tmat = Bone._tmpMats[0];
  73024. var tvec = Bone._tmpVecs[0];
  73025. if (this._parent) {
  73026. if (mesh && wm) {
  73027. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73028. tmat.multiplyToRef(wm, tmat);
  73029. }
  73030. else {
  73031. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73032. }
  73033. }
  73034. tmat.m[12] = 0;
  73035. tmat.m[13] = 0;
  73036. tmat.m[14] = 0;
  73037. tmat.invert();
  73038. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  73039. lm.m[12] += tvec.x;
  73040. lm.m[13] += tvec.y;
  73041. lm.m[14] += tvec.z;
  73042. }
  73043. this.markAsDirty();
  73044. };
  73045. /**
  73046. * Set the postion of the bone in local or world space.
  73047. * @param position The position to set the bone.
  73048. * @param space The space that the position is in.
  73049. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73050. */
  73051. Bone.prototype.setPosition = function (position, space, mesh) {
  73052. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73053. var lm = this.getLocalMatrix();
  73054. if (space == BABYLON.Space.LOCAL) {
  73055. lm.m[12] = position.x;
  73056. lm.m[13] = position.y;
  73057. lm.m[14] = position.z;
  73058. }
  73059. else {
  73060. var wm = null;
  73061. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73062. if (mesh) {
  73063. wm = mesh.getWorldMatrix();
  73064. }
  73065. this._skeleton.computeAbsoluteTransforms();
  73066. var tmat = Bone._tmpMats[0];
  73067. var vec = Bone._tmpVecs[0];
  73068. if (this._parent) {
  73069. if (mesh && wm) {
  73070. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73071. tmat.multiplyToRef(wm, tmat);
  73072. }
  73073. else {
  73074. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73075. }
  73076. }
  73077. tmat.invert();
  73078. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  73079. lm.m[12] = vec.x;
  73080. lm.m[13] = vec.y;
  73081. lm.m[14] = vec.z;
  73082. }
  73083. this.markAsDirty();
  73084. };
  73085. /**
  73086. * Set the absolute postion of the bone (world space).
  73087. * @param position The position to set the bone.
  73088. * @param mesh The mesh that this bone is attached to.
  73089. */
  73090. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  73091. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  73092. };
  73093. /**
  73094. * Set the scale of the bone on the x, y and z axes.
  73095. * @param x The scale of the bone on the x axis.
  73096. * @param x The scale of the bone on the y axis.
  73097. * @param z The scale of the bone on the z axis.
  73098. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73099. */
  73100. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  73101. if (scaleChildren === void 0) { scaleChildren = false; }
  73102. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  73103. if (!scaleChildren) {
  73104. this._negateScaleChildren.x = 1 / x;
  73105. this._negateScaleChildren.y = 1 / y;
  73106. this._negateScaleChildren.z = 1 / z;
  73107. }
  73108. this._syncScaleVector();
  73109. }
  73110. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  73111. };
  73112. /**
  73113. * Scale the bone on the x, y and z axes.
  73114. * @param x The amount to scale the bone on the x axis.
  73115. * @param x The amount to scale the bone on the y axis.
  73116. * @param z The amount to scale the bone on the z axis.
  73117. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73118. */
  73119. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  73120. if (scaleChildren === void 0) { scaleChildren = false; }
  73121. var locMat = this.getLocalMatrix();
  73122. var origLocMat = Bone._tmpMats[0];
  73123. origLocMat.copyFrom(locMat);
  73124. var origLocMatInv = Bone._tmpMats[1];
  73125. origLocMatInv.copyFrom(origLocMat);
  73126. origLocMatInv.invert();
  73127. var scaleMat = Bone._tmpMats[2];
  73128. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  73129. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  73130. this._scaleVector.x *= x;
  73131. this._scaleVector.y *= y;
  73132. this._scaleVector.z *= z;
  73133. locMat.multiplyToRef(origLocMatInv, locMat);
  73134. locMat.multiplyToRef(scaleMat, locMat);
  73135. locMat.multiplyToRef(origLocMat, locMat);
  73136. var parent = this.getParent();
  73137. if (parent) {
  73138. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  73139. }
  73140. else {
  73141. this.getAbsoluteTransform().copyFrom(locMat);
  73142. }
  73143. var len = this.children.length;
  73144. scaleMat.invert();
  73145. for (var i = 0; i < len; i++) {
  73146. var child = this.children[i];
  73147. var cm = child.getLocalMatrix();
  73148. cm.multiplyToRef(scaleMat, cm);
  73149. var lm = child.getLocalMatrix();
  73150. lm.m[12] *= x;
  73151. lm.m[13] *= y;
  73152. lm.m[14] *= z;
  73153. }
  73154. this.computeAbsoluteTransforms();
  73155. if (scaleChildren) {
  73156. for (var i = 0; i < len; i++) {
  73157. this.children[i].scale(x, y, z, scaleChildren);
  73158. }
  73159. }
  73160. this.markAsDirty();
  73161. };
  73162. /**
  73163. * Set the yaw, pitch, and roll of the bone in local or world space.
  73164. * @param yaw The rotation of the bone on the y axis.
  73165. * @param pitch The rotation of the bone on the x axis.
  73166. * @param roll The rotation of the bone on the z axis.
  73167. * @param space The space that the axes of rotation are in.
  73168. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73169. */
  73170. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  73171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73172. var rotMat = Bone._tmpMats[0];
  73173. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  73174. var rotMatInv = Bone._tmpMats[1];
  73175. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73176. rotMatInv.multiplyToRef(rotMat, rotMat);
  73177. this._rotateWithMatrix(rotMat, space, mesh);
  73178. };
  73179. /**
  73180. * Rotate the bone on an axis in local or world space.
  73181. * @param axis The axis to rotate the bone on.
  73182. * @param amount The amount to rotate the bone.
  73183. * @param space The space that the axis is in.
  73184. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73185. */
  73186. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  73187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73188. var rmat = Bone._tmpMats[0];
  73189. rmat.m[12] = 0;
  73190. rmat.m[13] = 0;
  73191. rmat.m[14] = 0;
  73192. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  73193. this._rotateWithMatrix(rmat, space, mesh);
  73194. };
  73195. /**
  73196. * Set the rotation of the bone to a particular axis angle in local or world space.
  73197. * @param axis The axis to rotate the bone on.
  73198. * @param angle The angle that the bone should be rotated to.
  73199. * @param space The space that the axis is in.
  73200. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73201. */
  73202. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  73203. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73204. var rotMat = Bone._tmpMats[0];
  73205. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  73206. var rotMatInv = Bone._tmpMats[1];
  73207. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73208. rotMatInv.multiplyToRef(rotMat, rotMat);
  73209. this._rotateWithMatrix(rotMat, space, mesh);
  73210. };
  73211. /**
  73212. * Set the euler rotation of the bone in local of world space.
  73213. * @param rotation The euler rotation that the bone should be set to.
  73214. * @param space The space that the rotation is in.
  73215. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73216. */
  73217. Bone.prototype.setRotation = function (rotation, space, mesh) {
  73218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73219. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  73220. };
  73221. /**
  73222. * Set the quaternion rotation of the bone in local of world space.
  73223. * @param quat The quaternion rotation that the bone should be set to.
  73224. * @param space The space that the rotation is in.
  73225. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73226. */
  73227. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  73228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73229. var rotMatInv = Bone._tmpMats[0];
  73230. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73231. var rotMat = Bone._tmpMats[1];
  73232. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  73233. rotMatInv.multiplyToRef(rotMat, rotMat);
  73234. this._rotateWithMatrix(rotMat, space, mesh);
  73235. };
  73236. /**
  73237. * Set the rotation matrix of the bone in local of world space.
  73238. * @param rotMat The rotation matrix that the bone should be set to.
  73239. * @param space The space that the rotation is in.
  73240. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73241. */
  73242. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73243. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73244. var rotMatInv = Bone._tmpMats[0];
  73245. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73246. var rotMat2 = Bone._tmpMats[1];
  73247. rotMat2.copyFrom(rotMat);
  73248. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73249. this._rotateWithMatrix(rotMat2, space, mesh);
  73250. };
  73251. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73253. var lmat = this.getLocalMatrix();
  73254. var lx = lmat.m[12];
  73255. var ly = lmat.m[13];
  73256. var lz = lmat.m[14];
  73257. var parent = this.getParent();
  73258. var parentScale = Bone._tmpMats[3];
  73259. var parentScaleInv = Bone._tmpMats[4];
  73260. if (parent) {
  73261. if (space == BABYLON.Space.WORLD) {
  73262. if (mesh) {
  73263. parentScale.copyFrom(mesh.getWorldMatrix());
  73264. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73265. }
  73266. else {
  73267. parentScale.copyFrom(parent.getAbsoluteTransform());
  73268. }
  73269. }
  73270. else {
  73271. parentScale = parent._scaleMatrix;
  73272. }
  73273. parentScaleInv.copyFrom(parentScale);
  73274. parentScaleInv.invert();
  73275. lmat.multiplyToRef(parentScale, lmat);
  73276. lmat.multiplyToRef(rmat, lmat);
  73277. lmat.multiplyToRef(parentScaleInv, lmat);
  73278. }
  73279. else {
  73280. if (space == BABYLON.Space.WORLD && mesh) {
  73281. parentScale.copyFrom(mesh.getWorldMatrix());
  73282. parentScaleInv.copyFrom(parentScale);
  73283. parentScaleInv.invert();
  73284. lmat.multiplyToRef(parentScale, lmat);
  73285. lmat.multiplyToRef(rmat, lmat);
  73286. lmat.multiplyToRef(parentScaleInv, lmat);
  73287. }
  73288. else {
  73289. lmat.multiplyToRef(rmat, lmat);
  73290. }
  73291. }
  73292. lmat.m[12] = lx;
  73293. lmat.m[13] = ly;
  73294. lmat.m[14] = lz;
  73295. this.computeAbsoluteTransforms();
  73296. this.markAsDirty();
  73297. };
  73298. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73299. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73300. if (space == BABYLON.Space.WORLD) {
  73301. var scaleMatrix = Bone._tmpMats[2];
  73302. scaleMatrix.copyFrom(this._scaleMatrix);
  73303. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73304. if (mesh) {
  73305. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73306. var meshScale = Bone._tmpMats[3];
  73307. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73308. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73309. }
  73310. rotMatInv.invert();
  73311. scaleMatrix.m[0] *= this._scalingDeterminant;
  73312. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73313. }
  73314. else {
  73315. rotMatInv.copyFrom(this.getLocalMatrix());
  73316. rotMatInv.invert();
  73317. var scaleMatrix = Bone._tmpMats[2];
  73318. scaleMatrix.copyFrom(this._scaleMatrix);
  73319. if (this._parent) {
  73320. var pscaleMatrix = Bone._tmpMats[3];
  73321. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73322. pscaleMatrix.invert();
  73323. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73324. }
  73325. else {
  73326. scaleMatrix.m[0] *= this._scalingDeterminant;
  73327. }
  73328. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73329. }
  73330. };
  73331. /**
  73332. * Get the scale of the bone
  73333. * @returns the scale of the bone
  73334. */
  73335. Bone.prototype.getScale = function () {
  73336. return this._scaleVector.clone();
  73337. };
  73338. /**
  73339. * Copy the scale of the bone to a vector3.
  73340. * @param result The vector3 to copy the scale to
  73341. */
  73342. Bone.prototype.getScaleToRef = function (result) {
  73343. result.copyFrom(this._scaleVector);
  73344. };
  73345. /**
  73346. * Get the position of the bone in local or world space.
  73347. * @param space The space that the returned position is in.
  73348. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73349. * @returns The position of the bone
  73350. */
  73351. Bone.prototype.getPosition = function (space, mesh) {
  73352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73353. if (mesh === void 0) { mesh = null; }
  73354. var pos = BABYLON.Vector3.Zero();
  73355. this.getPositionToRef(space, mesh, pos);
  73356. return pos;
  73357. };
  73358. /**
  73359. * Copy the position of the bone to a vector3 in local or world space.
  73360. * @param space The space that the returned position is in.
  73361. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73362. * @param result The vector3 to copy the position to.
  73363. */
  73364. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73365. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73366. if (space == BABYLON.Space.LOCAL) {
  73367. var lm = this.getLocalMatrix();
  73368. result.x = lm.m[12];
  73369. result.y = lm.m[13];
  73370. result.z = lm.m[14];
  73371. }
  73372. else {
  73373. var wm = null;
  73374. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73375. if (mesh) {
  73376. wm = mesh.getWorldMatrix();
  73377. }
  73378. this._skeleton.computeAbsoluteTransforms();
  73379. var tmat = Bone._tmpMats[0];
  73380. if (mesh && wm) {
  73381. tmat.copyFrom(this.getAbsoluteTransform());
  73382. tmat.multiplyToRef(wm, tmat);
  73383. }
  73384. else {
  73385. tmat = this.getAbsoluteTransform();
  73386. }
  73387. result.x = tmat.m[12];
  73388. result.y = tmat.m[13];
  73389. result.z = tmat.m[14];
  73390. }
  73391. };
  73392. /**
  73393. * Get the absolute position of the bone (world space).
  73394. * @param mesh The mesh that this bone is attached to.
  73395. * @returns The absolute position of the bone
  73396. */
  73397. Bone.prototype.getAbsolutePosition = function (mesh) {
  73398. if (mesh === void 0) { mesh = null; }
  73399. var pos = BABYLON.Vector3.Zero();
  73400. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73401. return pos;
  73402. };
  73403. /**
  73404. * Copy the absolute position of the bone (world space) to the result param.
  73405. * @param mesh The mesh that this bone is attached to.
  73406. * @param result The vector3 to copy the absolute position to.
  73407. */
  73408. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73409. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73410. };
  73411. /**
  73412. * Compute the absolute transforms of this bone and its children.
  73413. */
  73414. Bone.prototype.computeAbsoluteTransforms = function () {
  73415. if (this._parent) {
  73416. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73417. }
  73418. else {
  73419. this._absoluteTransform.copyFrom(this._localMatrix);
  73420. var poseMatrix = this._skeleton.getPoseMatrix();
  73421. if (poseMatrix) {
  73422. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73423. }
  73424. }
  73425. var children = this.children;
  73426. var len = children.length;
  73427. for (var i = 0; i < len; i++) {
  73428. children[i].computeAbsoluteTransforms();
  73429. }
  73430. };
  73431. Bone.prototype._syncScaleVector = function () {
  73432. var lm = this.getLocalMatrix();
  73433. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73434. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73435. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73436. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73437. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73438. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73439. this._scaleVector.x = xs * Math.sqrt(xsq);
  73440. this._scaleVector.y = ys * Math.sqrt(ysq);
  73441. this._scaleVector.z = zs * Math.sqrt(zsq);
  73442. if (this._parent) {
  73443. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73444. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73445. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73446. }
  73447. 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);
  73448. };
  73449. /**
  73450. * Get the world direction from an axis that is in the local space of the bone.
  73451. * @param localAxis The local direction that is used to compute the world direction.
  73452. * @param mesh The mesh that this bone is attached to.
  73453. * @returns The world direction
  73454. */
  73455. Bone.prototype.getDirection = function (localAxis, mesh) {
  73456. if (mesh === void 0) { mesh = null; }
  73457. var result = BABYLON.Vector3.Zero();
  73458. this.getDirectionToRef(localAxis, mesh, result);
  73459. return result;
  73460. };
  73461. /**
  73462. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73463. * @param localAxis The local direction that is used to compute the world direction.
  73464. * @param mesh The mesh that this bone is attached to.
  73465. * @param result The vector3 that the world direction will be copied to.
  73466. */
  73467. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73468. if (mesh === void 0) { mesh = null; }
  73469. var wm = null;
  73470. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73471. if (mesh) {
  73472. wm = mesh.getWorldMatrix();
  73473. }
  73474. this._skeleton.computeAbsoluteTransforms();
  73475. var mat = Bone._tmpMats[0];
  73476. mat.copyFrom(this.getAbsoluteTransform());
  73477. if (mesh && wm) {
  73478. mat.multiplyToRef(wm, mat);
  73479. }
  73480. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73481. result.normalize();
  73482. };
  73483. /**
  73484. * Get the euler rotation of the bone in local or world space.
  73485. * @param space The space that the rotation should be in.
  73486. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73487. * @returns The euler rotation
  73488. */
  73489. Bone.prototype.getRotation = function (space, mesh) {
  73490. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73491. if (mesh === void 0) { mesh = null; }
  73492. var result = BABYLON.Vector3.Zero();
  73493. this.getRotationToRef(space, mesh, result);
  73494. return result;
  73495. };
  73496. /**
  73497. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73498. * @param space The space that the rotation should be in.
  73499. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73500. * @param result The vector3 that the rotation should be copied to.
  73501. */
  73502. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73503. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73504. if (mesh === void 0) { mesh = null; }
  73505. var quat = Bone._tmpQuat;
  73506. this.getRotationQuaternionToRef(space, mesh, quat);
  73507. quat.toEulerAnglesToRef(result);
  73508. };
  73509. /**
  73510. * Get the quaternion rotation of the bone in either local or world space.
  73511. * @param space The space that the rotation should be in.
  73512. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73513. * @returns The quaternion rotation
  73514. */
  73515. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73516. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73517. if (mesh === void 0) { mesh = null; }
  73518. var result = BABYLON.Quaternion.Identity();
  73519. this.getRotationQuaternionToRef(space, mesh, result);
  73520. return result;
  73521. };
  73522. /**
  73523. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73524. * @param space The space that the rotation should be in.
  73525. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73526. * @param result The quaternion that the rotation should be copied to.
  73527. */
  73528. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73529. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73530. if (mesh === void 0) { mesh = null; }
  73531. if (space == BABYLON.Space.LOCAL) {
  73532. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73533. }
  73534. else {
  73535. var mat = Bone._tmpMats[0];
  73536. var amat = this.getAbsoluteTransform();
  73537. if (mesh) {
  73538. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73539. }
  73540. else {
  73541. mat.copyFrom(amat);
  73542. }
  73543. mat.m[0] *= this._scalingDeterminant;
  73544. mat.m[1] *= this._scalingDeterminant;
  73545. mat.m[2] *= this._scalingDeterminant;
  73546. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73547. }
  73548. };
  73549. /**
  73550. * Get the rotation matrix of the bone in local or world space.
  73551. * @param space The space that the rotation should be in.
  73552. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73553. * @returns The rotation matrix
  73554. */
  73555. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73556. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73557. var result = BABYLON.Matrix.Identity();
  73558. this.getRotationMatrixToRef(space, mesh, result);
  73559. return result;
  73560. };
  73561. /**
  73562. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73563. * @param space The space that the rotation should be in.
  73564. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73565. * @param result The quaternion that the rotation should be copied to.
  73566. */
  73567. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73568. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73569. if (space == BABYLON.Space.LOCAL) {
  73570. this.getLocalMatrix().getRotationMatrixToRef(result);
  73571. }
  73572. else {
  73573. var mat = Bone._tmpMats[0];
  73574. var amat = this.getAbsoluteTransform();
  73575. if (mesh) {
  73576. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73577. }
  73578. else {
  73579. mat.copyFrom(amat);
  73580. }
  73581. mat.m[0] *= this._scalingDeterminant;
  73582. mat.m[1] *= this._scalingDeterminant;
  73583. mat.m[2] *= this._scalingDeterminant;
  73584. mat.getRotationMatrixToRef(result);
  73585. }
  73586. };
  73587. /**
  73588. * Get the world position of a point that is in the local space of the bone.
  73589. * @param position The local position
  73590. * @param mesh The mesh that this bone is attached to.
  73591. * @returns The world position
  73592. */
  73593. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73594. if (mesh === void 0) { mesh = null; }
  73595. var result = BABYLON.Vector3.Zero();
  73596. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73597. return result;
  73598. };
  73599. /**
  73600. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73601. * @param position The local position
  73602. * @param mesh The mesh that this bone is attached to.
  73603. * @param result The vector3 that the world position should be copied to.
  73604. */
  73605. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73606. if (mesh === void 0) { mesh = null; }
  73607. var wm = null;
  73608. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73609. if (mesh) {
  73610. wm = mesh.getWorldMatrix();
  73611. }
  73612. this._skeleton.computeAbsoluteTransforms();
  73613. var tmat = Bone._tmpMats[0];
  73614. if (mesh && wm) {
  73615. tmat.copyFrom(this.getAbsoluteTransform());
  73616. tmat.multiplyToRef(wm, tmat);
  73617. }
  73618. else {
  73619. tmat = this.getAbsoluteTransform();
  73620. }
  73621. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73622. };
  73623. /**
  73624. * Get the local position of a point that is in world space.
  73625. * @param position The world position
  73626. * @param mesh The mesh that this bone is attached to.
  73627. * @returns The local position
  73628. */
  73629. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73630. if (mesh === void 0) { mesh = null; }
  73631. var result = BABYLON.Vector3.Zero();
  73632. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73633. return result;
  73634. };
  73635. /**
  73636. * Get the local position of a point that is in world space and copy it to the result param.
  73637. * @param position The world position
  73638. * @param mesh The mesh that this bone is attached to.
  73639. * @param result The vector3 that the local position should be copied to.
  73640. */
  73641. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73642. if (mesh === void 0) { mesh = null; }
  73643. var wm = null;
  73644. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73645. if (mesh) {
  73646. wm = mesh.getWorldMatrix();
  73647. }
  73648. this._skeleton.computeAbsoluteTransforms();
  73649. var tmat = Bone._tmpMats[0];
  73650. tmat.copyFrom(this.getAbsoluteTransform());
  73651. if (mesh && wm) {
  73652. tmat.multiplyToRef(wm, tmat);
  73653. }
  73654. tmat.invert();
  73655. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73656. };
  73657. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73658. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73659. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73660. return Bone;
  73661. }(BABYLON.Node));
  73662. BABYLON.Bone = Bone;
  73663. })(BABYLON || (BABYLON = {}));
  73664. //# sourceMappingURL=babylon.bone.js.map
  73665. "use strict";
  73666. var BABYLON;
  73667. (function (BABYLON) {
  73668. var BoneIKController = /** @class */ (function () {
  73669. function BoneIKController(mesh, bone, options) {
  73670. this.targetPosition = BABYLON.Vector3.Zero();
  73671. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73672. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73673. this.poleAngle = 0;
  73674. this.slerpAmount = 1;
  73675. this._bone1Quat = BABYLON.Quaternion.Identity();
  73676. this._bone1Mat = BABYLON.Matrix.Identity();
  73677. this._bone2Ang = Math.PI;
  73678. this._maxAngle = Math.PI;
  73679. this._rightHandedSystem = false;
  73680. this._bendAxis = BABYLON.Vector3.Right();
  73681. this._slerping = false;
  73682. this._adjustRoll = 0;
  73683. this._bone2 = bone;
  73684. this._bone1 = bone.getParent();
  73685. if (!this._bone1) {
  73686. return;
  73687. }
  73688. this.mesh = mesh;
  73689. var bonePos = bone.getPosition();
  73690. if (bone.getAbsoluteTransform().determinant() > 0) {
  73691. this._rightHandedSystem = true;
  73692. this._bendAxis.x = 0;
  73693. this._bendAxis.y = 0;
  73694. this._bendAxis.z = -1;
  73695. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73696. this._adjustRoll = Math.PI * .5;
  73697. this._bendAxis.z = 1;
  73698. }
  73699. }
  73700. if (this._bone1.length) {
  73701. var boneScale1 = this._bone1.getScale();
  73702. var boneScale2 = this._bone2.getScale();
  73703. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73704. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73705. }
  73706. else if (this._bone1.children[0]) {
  73707. mesh.computeWorldMatrix(true);
  73708. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73709. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73710. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73711. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73712. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73713. }
  73714. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73715. this.maxAngle = Math.PI;
  73716. if (options) {
  73717. if (options.targetMesh) {
  73718. this.targetMesh = options.targetMesh;
  73719. this.targetMesh.computeWorldMatrix(true);
  73720. }
  73721. if (options.poleTargetMesh) {
  73722. this.poleTargetMesh = options.poleTargetMesh;
  73723. this.poleTargetMesh.computeWorldMatrix(true);
  73724. }
  73725. else if (options.poleTargetBone) {
  73726. this.poleTargetBone = options.poleTargetBone;
  73727. }
  73728. else if (this._bone1.getParent()) {
  73729. this.poleTargetBone = this._bone1.getParent();
  73730. }
  73731. if (options.poleTargetLocalOffset) {
  73732. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73733. }
  73734. if (options.poleAngle) {
  73735. this.poleAngle = options.poleAngle;
  73736. }
  73737. if (options.bendAxis) {
  73738. this._bendAxis.copyFrom(options.bendAxis);
  73739. }
  73740. if (options.maxAngle) {
  73741. this.maxAngle = options.maxAngle;
  73742. }
  73743. if (options.slerpAmount) {
  73744. this.slerpAmount = options.slerpAmount;
  73745. }
  73746. }
  73747. }
  73748. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73749. get: function () {
  73750. return this._maxAngle;
  73751. },
  73752. set: function (value) {
  73753. this._setMaxAngle(value);
  73754. },
  73755. enumerable: true,
  73756. configurable: true
  73757. });
  73758. BoneIKController.prototype._setMaxAngle = function (ang) {
  73759. if (ang < 0) {
  73760. ang = 0;
  73761. }
  73762. if (ang > Math.PI || ang == undefined) {
  73763. ang = Math.PI;
  73764. }
  73765. this._maxAngle = ang;
  73766. var a = this._bone1Length;
  73767. var b = this._bone2Length;
  73768. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73769. };
  73770. BoneIKController.prototype.update = function () {
  73771. var bone1 = this._bone1;
  73772. if (!bone1) {
  73773. return;
  73774. }
  73775. var target = this.targetPosition;
  73776. var poleTarget = this.poleTargetPosition;
  73777. var mat1 = BoneIKController._tmpMats[0];
  73778. var mat2 = BoneIKController._tmpMats[1];
  73779. if (this.targetMesh) {
  73780. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73781. }
  73782. if (this.poleTargetBone) {
  73783. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73784. }
  73785. else if (this.poleTargetMesh) {
  73786. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73787. }
  73788. var bonePos = BoneIKController._tmpVecs[0];
  73789. var zaxis = BoneIKController._tmpVecs[1];
  73790. var xaxis = BoneIKController._tmpVecs[2];
  73791. var yaxis = BoneIKController._tmpVecs[3];
  73792. var upAxis = BoneIKController._tmpVecs[4];
  73793. var _tmpQuat = BoneIKController._tmpQuat;
  73794. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73795. poleTarget.subtractToRef(bonePos, upAxis);
  73796. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73797. upAxis.y = 1;
  73798. }
  73799. else {
  73800. upAxis.normalize();
  73801. }
  73802. target.subtractToRef(bonePos, yaxis);
  73803. yaxis.normalize();
  73804. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73805. zaxis.normalize();
  73806. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73807. xaxis.normalize();
  73808. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73809. var a = this._bone1Length;
  73810. var b = this._bone2Length;
  73811. var c = BABYLON.Vector3.Distance(bonePos, target);
  73812. if (this._maxReach > 0) {
  73813. c = Math.min(this._maxReach, c);
  73814. }
  73815. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73816. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73817. if (acosa > 1) {
  73818. acosa = 1;
  73819. }
  73820. if (acosb > 1) {
  73821. acosb = 1;
  73822. }
  73823. if (acosa < -1) {
  73824. acosa = -1;
  73825. }
  73826. if (acosb < -1) {
  73827. acosb = -1;
  73828. }
  73829. var angA = Math.acos(acosa);
  73830. var angB = Math.acos(acosb);
  73831. var angC = -angA - angB;
  73832. if (this._rightHandedSystem) {
  73833. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73834. mat2.multiplyToRef(mat1, mat1);
  73835. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73836. mat2.multiplyToRef(mat1, mat1);
  73837. }
  73838. else {
  73839. var _tmpVec = BoneIKController._tmpVecs[5];
  73840. _tmpVec.copyFrom(this._bendAxis);
  73841. _tmpVec.x *= -1;
  73842. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73843. mat2.multiplyToRef(mat1, mat1);
  73844. }
  73845. if (this.poleAngle) {
  73846. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73847. mat1.multiplyToRef(mat2, mat1);
  73848. }
  73849. if (this._bone1) {
  73850. if (this.slerpAmount < 1) {
  73851. if (!this._slerping) {
  73852. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73853. }
  73854. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73855. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73856. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73857. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73858. this._slerping = true;
  73859. }
  73860. else {
  73861. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73862. this._bone1Mat.copyFrom(mat1);
  73863. this._slerping = false;
  73864. }
  73865. }
  73866. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73867. this._bone2Ang = angC;
  73868. };
  73869. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73870. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73871. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73872. return BoneIKController;
  73873. }());
  73874. BABYLON.BoneIKController = BoneIKController;
  73875. })(BABYLON || (BABYLON = {}));
  73876. //# sourceMappingURL=babylon.boneIKController.js.map
  73877. "use strict";
  73878. var BABYLON;
  73879. (function (BABYLON) {
  73880. var BoneLookController = /** @class */ (function () {
  73881. /**
  73882. * Create a BoneLookController
  73883. * @param mesh the mesh that the bone belongs to
  73884. * @param bone the bone that will be looking to the target
  73885. * @param target the target Vector3 to look at
  73886. * @param settings optional settings:
  73887. * - maxYaw: the maximum angle the bone will yaw to
  73888. * - minYaw: the minimum angle the bone will yaw to
  73889. * - maxPitch: the maximum angle the bone will pitch to
  73890. * - minPitch: the minimum angle the bone will yaw to
  73891. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73892. * - upAxis: the up axis of the coordinate system
  73893. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73894. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73895. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73896. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73897. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73898. * - adjustRoll: used to make an adjustment to the roll of the bone
  73899. **/
  73900. function BoneLookController(mesh, bone, target, options) {
  73901. /**
  73902. * The up axis of the coordinate system that is used when the bone is rotated.
  73903. */
  73904. this.upAxis = BABYLON.Vector3.Up();
  73905. /**
  73906. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73907. */
  73908. this.upAxisSpace = BABYLON.Space.LOCAL;
  73909. /**
  73910. * Used to make an adjustment to the yaw of the bone.
  73911. */
  73912. this.adjustYaw = 0;
  73913. /**
  73914. * Used to make an adjustment to the pitch of the bone.
  73915. */
  73916. this.adjustPitch = 0;
  73917. /**
  73918. * Used to make an adjustment to the roll of the bone.
  73919. */
  73920. this.adjustRoll = 0;
  73921. /**
  73922. * 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).
  73923. */
  73924. this.slerpAmount = 1;
  73925. this._boneQuat = BABYLON.Quaternion.Identity();
  73926. this._slerping = false;
  73927. this._firstFrameSkipped = false;
  73928. this._fowardAxis = BABYLON.Vector3.Forward();
  73929. this.mesh = mesh;
  73930. this.bone = bone;
  73931. this.target = target;
  73932. if (options) {
  73933. if (options.adjustYaw) {
  73934. this.adjustYaw = options.adjustYaw;
  73935. }
  73936. if (options.adjustPitch) {
  73937. this.adjustPitch = options.adjustPitch;
  73938. }
  73939. if (options.adjustRoll) {
  73940. this.adjustRoll = options.adjustRoll;
  73941. }
  73942. if (options.maxYaw != null) {
  73943. this.maxYaw = options.maxYaw;
  73944. }
  73945. else {
  73946. this.maxYaw = Math.PI;
  73947. }
  73948. if (options.minYaw != null) {
  73949. this.minYaw = options.minYaw;
  73950. }
  73951. else {
  73952. this.minYaw = -Math.PI;
  73953. }
  73954. if (options.maxPitch != null) {
  73955. this.maxPitch = options.maxPitch;
  73956. }
  73957. else {
  73958. this.maxPitch = Math.PI;
  73959. }
  73960. if (options.minPitch != null) {
  73961. this.minPitch = options.minPitch;
  73962. }
  73963. else {
  73964. this.minPitch = -Math.PI;
  73965. }
  73966. if (options.slerpAmount != null) {
  73967. this.slerpAmount = options.slerpAmount;
  73968. }
  73969. if (options.upAxis != null) {
  73970. this.upAxis = options.upAxis;
  73971. }
  73972. if (options.upAxisSpace != null) {
  73973. this.upAxisSpace = options.upAxisSpace;
  73974. }
  73975. if (options.yawAxis != null || options.pitchAxis != null) {
  73976. var newYawAxis = BABYLON.Axis.Y;
  73977. var newPitchAxis = BABYLON.Axis.X;
  73978. if (options.yawAxis != null) {
  73979. newYawAxis = options.yawAxis.clone();
  73980. newYawAxis.normalize();
  73981. }
  73982. if (options.pitchAxis != null) {
  73983. newPitchAxis = options.pitchAxis.clone();
  73984. newPitchAxis.normalize();
  73985. }
  73986. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73987. this._transformYawPitch = BABYLON.Matrix.Identity();
  73988. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73989. this._transformYawPitchInv = this._transformYawPitch.clone();
  73990. this._transformYawPitch.invert();
  73991. }
  73992. }
  73993. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73994. this.upAxisSpace = BABYLON.Space.LOCAL;
  73995. }
  73996. }
  73997. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73998. /**
  73999. * Get/set the minimum yaw angle that the bone can look to.
  74000. */
  74001. get: function () {
  74002. return this._minYaw;
  74003. },
  74004. set: function (value) {
  74005. this._minYaw = value;
  74006. this._minYawSin = Math.sin(value);
  74007. this._minYawCos = Math.cos(value);
  74008. if (this._maxYaw != null) {
  74009. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  74010. this._yawRange = this._maxYaw - this._minYaw;
  74011. }
  74012. },
  74013. enumerable: true,
  74014. configurable: true
  74015. });
  74016. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  74017. /**
  74018. * Get/set the maximum yaw angle that the bone can look to.
  74019. */
  74020. get: function () {
  74021. return this._maxYaw;
  74022. },
  74023. set: function (value) {
  74024. this._maxYaw = value;
  74025. this._maxYawSin = Math.sin(value);
  74026. this._maxYawCos = Math.cos(value);
  74027. if (this._minYaw != null) {
  74028. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  74029. this._yawRange = this._maxYaw - this._minYaw;
  74030. }
  74031. },
  74032. enumerable: true,
  74033. configurable: true
  74034. });
  74035. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  74036. /**
  74037. * Get/set the minimum pitch angle that the bone can look to.
  74038. */
  74039. get: function () {
  74040. return this._minPitch;
  74041. },
  74042. set: function (value) {
  74043. this._minPitch = value;
  74044. this._minPitchTan = Math.tan(value);
  74045. },
  74046. enumerable: true,
  74047. configurable: true
  74048. });
  74049. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  74050. /**
  74051. * Get/set the maximum pitch angle that the bone can look to.
  74052. */
  74053. get: function () {
  74054. return this._maxPitch;
  74055. },
  74056. set: function (value) {
  74057. this._maxPitch = value;
  74058. this._maxPitchTan = Math.tan(value);
  74059. },
  74060. enumerable: true,
  74061. configurable: true
  74062. });
  74063. /**
  74064. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  74065. */
  74066. BoneLookController.prototype.update = function () {
  74067. //skip the first frame when slerping so that the mesh rotation is correct
  74068. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  74069. this._firstFrameSkipped = true;
  74070. return;
  74071. }
  74072. var bone = this.bone;
  74073. var bonePos = BoneLookController._tmpVecs[0];
  74074. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  74075. var target = this.target;
  74076. var _tmpMat1 = BoneLookController._tmpMats[0];
  74077. var _tmpMat2 = BoneLookController._tmpMats[1];
  74078. var mesh = this.mesh;
  74079. var parentBone = bone.getParent();
  74080. var upAxis = BoneLookController._tmpVecs[1];
  74081. upAxis.copyFrom(this.upAxis);
  74082. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  74083. if (this._transformYawPitch) {
  74084. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  74085. }
  74086. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  74087. }
  74088. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  74089. mesh.getDirectionToRef(upAxis, upAxis);
  74090. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  74091. upAxis.normalize();
  74092. }
  74093. }
  74094. var checkYaw = false;
  74095. var checkPitch = false;
  74096. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  74097. checkYaw = true;
  74098. }
  74099. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  74100. checkPitch = true;
  74101. }
  74102. if (checkYaw || checkPitch) {
  74103. var spaceMat = BoneLookController._tmpMats[2];
  74104. var spaceMatInv = BoneLookController._tmpMats[3];
  74105. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  74106. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  74107. }
  74108. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  74109. spaceMat.copyFrom(mesh.getWorldMatrix());
  74110. }
  74111. else {
  74112. var forwardAxis = BoneLookController._tmpVecs[2];
  74113. forwardAxis.copyFrom(this._fowardAxis);
  74114. if (this._transformYawPitch) {
  74115. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  74116. }
  74117. if (parentBone) {
  74118. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  74119. }
  74120. else {
  74121. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  74122. }
  74123. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  74124. rightAxis.normalize();
  74125. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  74126. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  74127. }
  74128. spaceMat.invertToRef(spaceMatInv);
  74129. var xzlen = null;
  74130. if (checkPitch) {
  74131. var localTarget = BoneLookController._tmpVecs[3];
  74132. target.subtractToRef(bonePos, localTarget);
  74133. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74134. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74135. var pitch = Math.atan2(localTarget.y, xzlen);
  74136. var newPitch = pitch;
  74137. if (pitch > this._maxPitch) {
  74138. localTarget.y = this._maxPitchTan * xzlen;
  74139. newPitch = this._maxPitch;
  74140. }
  74141. else if (pitch < this._minPitch) {
  74142. localTarget.y = this._minPitchTan * xzlen;
  74143. newPitch = this._minPitch;
  74144. }
  74145. if (pitch != newPitch) {
  74146. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74147. localTarget.addInPlace(bonePos);
  74148. target = localTarget;
  74149. }
  74150. }
  74151. if (checkYaw) {
  74152. var localTarget = BoneLookController._tmpVecs[4];
  74153. target.subtractToRef(bonePos, localTarget);
  74154. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74155. var yaw = Math.atan2(localTarget.x, localTarget.z);
  74156. var newYaw = yaw;
  74157. if (yaw > this._maxYaw || yaw < this._minYaw) {
  74158. if (xzlen == null) {
  74159. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74160. }
  74161. if (this._yawRange > Math.PI) {
  74162. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  74163. localTarget.z = this._maxYawCos * xzlen;
  74164. localTarget.x = this._maxYawSin * xzlen;
  74165. newYaw = this._maxYaw;
  74166. }
  74167. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  74168. localTarget.z = this._minYawCos * xzlen;
  74169. localTarget.x = this._minYawSin * xzlen;
  74170. newYaw = this._minYaw;
  74171. }
  74172. }
  74173. else {
  74174. if (yaw > this._maxYaw) {
  74175. localTarget.z = this._maxYawCos * xzlen;
  74176. localTarget.x = this._maxYawSin * xzlen;
  74177. newYaw = this._maxYaw;
  74178. }
  74179. else if (yaw < this._minYaw) {
  74180. localTarget.z = this._minYawCos * xzlen;
  74181. localTarget.x = this._minYawSin * xzlen;
  74182. newYaw = this._minYaw;
  74183. }
  74184. }
  74185. }
  74186. if (this._slerping && this._yawRange > Math.PI) {
  74187. //are we going to be crossing into the min/max region?
  74188. var boneFwd = BoneLookController._tmpVecs[8];
  74189. boneFwd.copyFrom(BABYLON.Axis.Z);
  74190. if (this._transformYawPitch) {
  74191. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  74192. }
  74193. var boneRotMat = BoneLookController._tmpMats[4];
  74194. this._boneQuat.toRotationMatrix(boneRotMat);
  74195. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  74196. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  74197. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  74198. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  74199. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  74200. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  74201. if (angBtwTar > angBtwMidYaw) {
  74202. if (xzlen == null) {
  74203. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74204. }
  74205. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  74206. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  74207. if (angBtwMin < angBtwMax) {
  74208. newYaw = boneYaw + Math.PI * .75;
  74209. localTarget.z = Math.cos(newYaw) * xzlen;
  74210. localTarget.x = Math.sin(newYaw) * xzlen;
  74211. }
  74212. else {
  74213. newYaw = boneYaw - Math.PI * .75;
  74214. localTarget.z = Math.cos(newYaw) * xzlen;
  74215. localTarget.x = Math.sin(newYaw) * xzlen;
  74216. }
  74217. }
  74218. }
  74219. if (yaw != newYaw) {
  74220. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74221. localTarget.addInPlace(bonePos);
  74222. target = localTarget;
  74223. }
  74224. }
  74225. }
  74226. var zaxis = BoneLookController._tmpVecs[5];
  74227. var xaxis = BoneLookController._tmpVecs[6];
  74228. var yaxis = BoneLookController._tmpVecs[7];
  74229. var _tmpQuat = BoneLookController._tmpQuat;
  74230. target.subtractToRef(bonePos, zaxis);
  74231. zaxis.normalize();
  74232. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  74233. xaxis.normalize();
  74234. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  74235. yaxis.normalize();
  74236. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  74237. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74238. return;
  74239. }
  74240. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74241. return;
  74242. }
  74243. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74244. return;
  74245. }
  74246. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74247. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74248. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74249. }
  74250. if (this.slerpAmount < 1) {
  74251. if (!this._slerping) {
  74252. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74253. }
  74254. if (this._transformYawPitch) {
  74255. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74256. }
  74257. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74258. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74259. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74260. this._slerping = true;
  74261. }
  74262. else {
  74263. if (this._transformYawPitch) {
  74264. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74265. }
  74266. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74267. this._slerping = false;
  74268. }
  74269. };
  74270. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74271. var angDiff = ang2 - ang1;
  74272. angDiff %= Math.PI * 2;
  74273. if (angDiff > Math.PI) {
  74274. angDiff -= Math.PI * 2;
  74275. }
  74276. else if (angDiff < -Math.PI) {
  74277. angDiff += Math.PI * 2;
  74278. }
  74279. return angDiff;
  74280. };
  74281. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74282. ang1 %= (2 * Math.PI);
  74283. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74284. ang2 %= (2 * Math.PI);
  74285. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74286. var ab = 0;
  74287. if (ang1 < ang2) {
  74288. ab = ang2 - ang1;
  74289. }
  74290. else {
  74291. ab = ang1 - ang2;
  74292. }
  74293. if (ab > Math.PI) {
  74294. ab = Math.PI * 2 - ab;
  74295. }
  74296. return ab;
  74297. };
  74298. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74299. ang %= (2 * Math.PI);
  74300. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74301. ang1 %= (2 * Math.PI);
  74302. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74303. ang2 %= (2 * Math.PI);
  74304. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74305. if (ang1 < ang2) {
  74306. if (ang > ang1 && ang < ang2) {
  74307. return true;
  74308. }
  74309. }
  74310. else {
  74311. if (ang > ang2 && ang < ang1) {
  74312. return true;
  74313. }
  74314. }
  74315. return false;
  74316. };
  74317. 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()];
  74318. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74319. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74320. return BoneLookController;
  74321. }());
  74322. BABYLON.BoneLookController = BoneLookController;
  74323. })(BABYLON || (BABYLON = {}));
  74324. //# sourceMappingURL=babylon.boneLookController.js.map
  74325. "use strict";
  74326. var BABYLON;
  74327. (function (BABYLON) {
  74328. var Skeleton = /** @class */ (function () {
  74329. function Skeleton(name, id, scene) {
  74330. this.name = name;
  74331. this.id = id;
  74332. this.bones = new Array();
  74333. this.needInitialSkinMatrix = false;
  74334. this._isDirty = true;
  74335. this._meshesWithPoseMatrix = new Array();
  74336. this._identity = BABYLON.Matrix.Identity();
  74337. this._ranges = {};
  74338. this._lastAbsoluteTransformsUpdateId = -1;
  74339. /**
  74340. * Specifies if the skeleton should be serialized.
  74341. */
  74342. this.doNotSerialize = false;
  74343. // Events
  74344. /**
  74345. * An event triggered before computing the skeleton's matrices
  74346. * @type {BABYLON.Observable}
  74347. */
  74348. this.onBeforeComputeObservable = new BABYLON.Observable();
  74349. this.bones = [];
  74350. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74351. scene.skeletons.push(this);
  74352. //make sure it will recalculate the matrix next time prepare is called.
  74353. this._isDirty = true;
  74354. }
  74355. // Members
  74356. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74357. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74358. return mesh._bonesTransformMatrices;
  74359. }
  74360. if (!this._transformMatrices) {
  74361. this.prepare();
  74362. }
  74363. return this._transformMatrices;
  74364. };
  74365. Skeleton.prototype.getScene = function () {
  74366. return this._scene;
  74367. };
  74368. // Methods
  74369. /**
  74370. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74371. */
  74372. Skeleton.prototype.toString = function (fullDetails) {
  74373. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74374. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74375. if (fullDetails) {
  74376. ret += ", Ranges: {";
  74377. var first = true;
  74378. for (var name_1 in this._ranges) {
  74379. if (first) {
  74380. ret += ", ";
  74381. first = false;
  74382. }
  74383. ret += name_1;
  74384. }
  74385. ret += "}";
  74386. }
  74387. return ret;
  74388. };
  74389. /**
  74390. * Get bone's index searching by name
  74391. * @param {string} name is bone's name to search for
  74392. * @return {number} Indice of the bone. Returns -1 if not found
  74393. */
  74394. Skeleton.prototype.getBoneIndexByName = function (name) {
  74395. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74396. if (this.bones[boneIndex].name === name) {
  74397. return boneIndex;
  74398. }
  74399. }
  74400. return -1;
  74401. };
  74402. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74403. // check name not already in use
  74404. if (!this._ranges[name]) {
  74405. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74406. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74407. if (this.bones[i].animations[0]) {
  74408. this.bones[i].animations[0].createRange(name, from, to);
  74409. }
  74410. }
  74411. }
  74412. };
  74413. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74414. if (deleteFrames === void 0) { deleteFrames = true; }
  74415. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74416. if (this.bones[i].animations[0]) {
  74417. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74418. }
  74419. }
  74420. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74421. };
  74422. Skeleton.prototype.getAnimationRange = function (name) {
  74423. return this._ranges[name];
  74424. };
  74425. /**
  74426. * Returns as an Array, all AnimationRanges defined on this skeleton
  74427. */
  74428. Skeleton.prototype.getAnimationRanges = function () {
  74429. var animationRanges = [];
  74430. var name;
  74431. var i = 0;
  74432. for (name in this._ranges) {
  74433. animationRanges[i] = this._ranges[name];
  74434. i++;
  74435. }
  74436. return animationRanges;
  74437. };
  74438. /**
  74439. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74440. */
  74441. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74442. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74443. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74444. return false;
  74445. }
  74446. var ret = true;
  74447. var frameOffset = this._getHighestAnimationFrame() + 1;
  74448. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74449. var boneDict = {};
  74450. var sourceBones = source.bones;
  74451. var nBones;
  74452. var i;
  74453. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74454. boneDict[sourceBones[i].name] = sourceBones[i];
  74455. }
  74456. if (this.bones.length !== sourceBones.length) {
  74457. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74458. ret = false;
  74459. }
  74460. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74461. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74462. var boneName = this.bones[i].name;
  74463. var sourceBone = boneDict[boneName];
  74464. if (sourceBone) {
  74465. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74466. }
  74467. else {
  74468. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74469. ret = false;
  74470. }
  74471. }
  74472. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74473. var range = source.getAnimationRange(name);
  74474. if (range) {
  74475. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74476. }
  74477. return ret;
  74478. };
  74479. Skeleton.prototype.returnToRest = function () {
  74480. for (var index = 0; index < this.bones.length; index++) {
  74481. this.bones[index].returnToRest();
  74482. }
  74483. };
  74484. Skeleton.prototype._getHighestAnimationFrame = function () {
  74485. var ret = 0;
  74486. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74487. if (this.bones[i].animations[0]) {
  74488. var highest = this.bones[i].animations[0].getHighestFrame();
  74489. if (ret < highest) {
  74490. ret = highest;
  74491. }
  74492. }
  74493. }
  74494. return ret;
  74495. };
  74496. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74497. var range = this.getAnimationRange(name);
  74498. if (!range) {
  74499. return null;
  74500. }
  74501. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74502. };
  74503. Skeleton.prototype._markAsDirty = function () {
  74504. this._isDirty = true;
  74505. };
  74506. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74507. this._meshesWithPoseMatrix.push(mesh);
  74508. };
  74509. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74510. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74511. if (index > -1) {
  74512. this._meshesWithPoseMatrix.splice(index, 1);
  74513. }
  74514. };
  74515. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74516. this.onBeforeComputeObservable.notifyObservers(this);
  74517. for (var index = 0; index < this.bones.length; index++) {
  74518. var bone = this.bones[index];
  74519. var parentBone = bone.getParent();
  74520. if (parentBone) {
  74521. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74522. }
  74523. else {
  74524. if (initialSkinMatrix) {
  74525. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74526. }
  74527. else {
  74528. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74529. }
  74530. }
  74531. if (bone._index !== -1) {
  74532. var mappedIndex = bone._index === null ? index : bone._index;
  74533. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74534. }
  74535. }
  74536. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74537. };
  74538. Skeleton.prototype.prepare = function () {
  74539. if (!this._isDirty) {
  74540. return;
  74541. }
  74542. if (this.needInitialSkinMatrix) {
  74543. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74544. var mesh = this._meshesWithPoseMatrix[index];
  74545. var poseMatrix = mesh.getPoseMatrix();
  74546. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74547. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74548. }
  74549. if (this._synchronizedWithMesh !== mesh) {
  74550. this._synchronizedWithMesh = mesh;
  74551. // Prepare bones
  74552. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74553. var bone = this.bones[boneIndex];
  74554. if (!bone.getParent()) {
  74555. var matrix = bone.getBaseMatrix();
  74556. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74557. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74558. }
  74559. }
  74560. }
  74561. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74562. }
  74563. }
  74564. else {
  74565. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74566. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74567. }
  74568. this._computeTransformMatrices(this._transformMatrices, null);
  74569. }
  74570. this._isDirty = false;
  74571. this._scene._activeBones.addCount(this.bones.length, false);
  74572. };
  74573. Skeleton.prototype.getAnimatables = function () {
  74574. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74575. this._animatables = [];
  74576. for (var index = 0; index < this.bones.length; index++) {
  74577. this._animatables.push(this.bones[index]);
  74578. }
  74579. }
  74580. return this._animatables;
  74581. };
  74582. Skeleton.prototype.clone = function (name, id) {
  74583. var result = new Skeleton(name, id || name, this._scene);
  74584. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74585. for (var index = 0; index < this.bones.length; index++) {
  74586. var source = this.bones[index];
  74587. var parentBone = null;
  74588. var parent_1 = source.getParent();
  74589. if (parent_1) {
  74590. var parentIndex = this.bones.indexOf(parent_1);
  74591. parentBone = result.bones[parentIndex];
  74592. }
  74593. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74594. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74595. }
  74596. if (this._ranges) {
  74597. result._ranges = {};
  74598. for (var rangeName in this._ranges) {
  74599. var range = this._ranges[rangeName];
  74600. if (range) {
  74601. result._ranges[rangeName] = range.clone();
  74602. }
  74603. }
  74604. }
  74605. this._isDirty = true;
  74606. return result;
  74607. };
  74608. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74609. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74610. this.bones.forEach(function (bone) {
  74611. bone.animations.forEach(function (animation) {
  74612. animation.enableBlending = true;
  74613. animation.blendingSpeed = blendingSpeed;
  74614. });
  74615. });
  74616. };
  74617. Skeleton.prototype.dispose = function () {
  74618. this._meshesWithPoseMatrix = [];
  74619. // Animations
  74620. this.getScene().stopAnimation(this);
  74621. // Remove from scene
  74622. this.getScene().removeSkeleton(this);
  74623. };
  74624. Skeleton.prototype.serialize = function () {
  74625. var serializationObject = {};
  74626. serializationObject.name = this.name;
  74627. serializationObject.id = this.id;
  74628. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74629. serializationObject.bones = [];
  74630. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74631. for (var index = 0; index < this.bones.length; index++) {
  74632. var bone = this.bones[index];
  74633. var parent_2 = bone.getParent();
  74634. var serializedBone = {
  74635. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74636. name: bone.name,
  74637. matrix: bone.getBaseMatrix().toArray(),
  74638. rest: bone.getRestPose().toArray()
  74639. };
  74640. serializationObject.bones.push(serializedBone);
  74641. if (bone.length) {
  74642. serializedBone.length = bone.length;
  74643. }
  74644. if (bone.animations && bone.animations.length > 0) {
  74645. serializedBone.animation = bone.animations[0].serialize();
  74646. }
  74647. serializationObject.ranges = [];
  74648. for (var name in this._ranges) {
  74649. var source = this._ranges[name];
  74650. if (!source) {
  74651. continue;
  74652. }
  74653. var range = {};
  74654. range.name = name;
  74655. range.from = source.from;
  74656. range.to = source.to;
  74657. serializationObject.ranges.push(range);
  74658. }
  74659. }
  74660. return serializationObject;
  74661. };
  74662. Skeleton.Parse = function (parsedSkeleton, scene) {
  74663. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74664. if (parsedSkeleton.dimensionsAtRest) {
  74665. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74666. }
  74667. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74668. var index;
  74669. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74670. var parsedBone = parsedSkeleton.bones[index];
  74671. var parentBone = null;
  74672. if (parsedBone.parentBoneIndex > -1) {
  74673. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74674. }
  74675. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74676. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74677. if (parsedBone.length) {
  74678. bone.length = parsedBone.length;
  74679. }
  74680. if (parsedBone.animation) {
  74681. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74682. }
  74683. }
  74684. // placed after bones, so createAnimationRange can cascade down
  74685. if (parsedSkeleton.ranges) {
  74686. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74687. var data = parsedSkeleton.ranges[index];
  74688. skeleton.createAnimationRange(data.name, data.from, data.to);
  74689. }
  74690. }
  74691. return skeleton;
  74692. };
  74693. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74694. if (forceUpdate === void 0) { forceUpdate = false; }
  74695. var renderId = this._scene.getRenderId();
  74696. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74697. this.bones[0].computeAbsoluteTransforms();
  74698. this._lastAbsoluteTransformsUpdateId = renderId;
  74699. }
  74700. };
  74701. Skeleton.prototype.getPoseMatrix = function () {
  74702. var poseMatrix = null;
  74703. if (this._meshesWithPoseMatrix.length > 0) {
  74704. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74705. }
  74706. return poseMatrix;
  74707. };
  74708. Skeleton.prototype.sortBones = function () {
  74709. var bones = new Array();
  74710. var visited = new Array(this.bones.length);
  74711. for (var index = 0; index < this.bones.length; index++) {
  74712. this._sortBones(index, bones, visited);
  74713. }
  74714. this.bones = bones;
  74715. };
  74716. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74717. if (visited[index]) {
  74718. return;
  74719. }
  74720. visited[index] = true;
  74721. var bone = this.bones[index];
  74722. if (bone._index === undefined) {
  74723. bone._index = index;
  74724. }
  74725. var parentBone = bone.getParent();
  74726. if (parentBone) {
  74727. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74728. }
  74729. bones.push(bone);
  74730. };
  74731. return Skeleton;
  74732. }());
  74733. BABYLON.Skeleton = Skeleton;
  74734. })(BABYLON || (BABYLON = {}));
  74735. //# sourceMappingURL=babylon.skeleton.js.map
  74736. "use strict";
  74737. var BABYLON;
  74738. (function (BABYLON) {
  74739. var SphericalPolynomial = /** @class */ (function () {
  74740. function SphericalPolynomial() {
  74741. this.x = BABYLON.Vector3.Zero();
  74742. this.y = BABYLON.Vector3.Zero();
  74743. this.z = BABYLON.Vector3.Zero();
  74744. this.xx = BABYLON.Vector3.Zero();
  74745. this.yy = BABYLON.Vector3.Zero();
  74746. this.zz = BABYLON.Vector3.Zero();
  74747. this.xy = BABYLON.Vector3.Zero();
  74748. this.yz = BABYLON.Vector3.Zero();
  74749. this.zx = BABYLON.Vector3.Zero();
  74750. }
  74751. SphericalPolynomial.prototype.addAmbient = function (color) {
  74752. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74753. this.xx = this.xx.add(colorVector);
  74754. this.yy = this.yy.add(colorVector);
  74755. this.zz = this.zz.add(colorVector);
  74756. };
  74757. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74758. var result = new SphericalPolynomial();
  74759. result.x = harmonics.L11.scale(1.02333);
  74760. result.y = harmonics.L1_1.scale(1.02333);
  74761. result.z = harmonics.L10.scale(1.02333);
  74762. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74763. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74764. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74765. result.yz = harmonics.L2_1.scale(0.858086);
  74766. result.zx = harmonics.L21.scale(0.858086);
  74767. result.xy = harmonics.L2_2.scale(0.858086);
  74768. result.scale(1.0 / Math.PI);
  74769. return result;
  74770. };
  74771. SphericalPolynomial.prototype.scale = function (scale) {
  74772. this.x = this.x.scale(scale);
  74773. this.y = this.y.scale(scale);
  74774. this.z = this.z.scale(scale);
  74775. this.xx = this.xx.scale(scale);
  74776. this.yy = this.yy.scale(scale);
  74777. this.zz = this.zz.scale(scale);
  74778. this.yz = this.yz.scale(scale);
  74779. this.zx = this.zx.scale(scale);
  74780. this.xy = this.xy.scale(scale);
  74781. };
  74782. return SphericalPolynomial;
  74783. }());
  74784. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74785. var SphericalHarmonics = /** @class */ (function () {
  74786. function SphericalHarmonics() {
  74787. this.L00 = BABYLON.Vector3.Zero();
  74788. this.L1_1 = BABYLON.Vector3.Zero();
  74789. this.L10 = BABYLON.Vector3.Zero();
  74790. this.L11 = BABYLON.Vector3.Zero();
  74791. this.L2_2 = BABYLON.Vector3.Zero();
  74792. this.L2_1 = BABYLON.Vector3.Zero();
  74793. this.L20 = BABYLON.Vector3.Zero();
  74794. this.L21 = BABYLON.Vector3.Zero();
  74795. this.L22 = BABYLON.Vector3.Zero();
  74796. }
  74797. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74798. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74799. var c = colorVector.scale(deltaSolidAngle);
  74800. this.L00 = this.L00.add(c.scale(0.282095));
  74801. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74802. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74803. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74804. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74805. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74806. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74807. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74808. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74809. };
  74810. SphericalHarmonics.prototype.scale = function (scale) {
  74811. this.L00 = this.L00.scale(scale);
  74812. this.L1_1 = this.L1_1.scale(scale);
  74813. this.L10 = this.L10.scale(scale);
  74814. this.L11 = this.L11.scale(scale);
  74815. this.L2_2 = this.L2_2.scale(scale);
  74816. this.L2_1 = this.L2_1.scale(scale);
  74817. this.L20 = this.L20.scale(scale);
  74818. this.L21 = this.L21.scale(scale);
  74819. this.L22 = this.L22.scale(scale);
  74820. };
  74821. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74822. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74823. //
  74824. // E_lm = A_l * L_lm
  74825. //
  74826. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74827. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74828. // the scaling factors are given in equation 9.
  74829. // Constant (Band 0)
  74830. this.L00 = this.L00.scale(3.141593);
  74831. // Linear (Band 1)
  74832. this.L1_1 = this.L1_1.scale(2.094395);
  74833. this.L10 = this.L10.scale(2.094395);
  74834. this.L11 = this.L11.scale(2.094395);
  74835. // Quadratic (Band 2)
  74836. this.L2_2 = this.L2_2.scale(0.785398);
  74837. this.L2_1 = this.L2_1.scale(0.785398);
  74838. this.L20 = this.L20.scale(0.785398);
  74839. this.L21 = this.L21.scale(0.785398);
  74840. this.L22 = this.L22.scale(0.785398);
  74841. };
  74842. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74843. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74844. // L = (1/pi) * E * rho
  74845. //
  74846. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74847. this.scale(1.0 / Math.PI);
  74848. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74849. // (The pixel shader must apply albedo after texture fetches, etc).
  74850. };
  74851. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74852. var result = new SphericalHarmonics();
  74853. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74854. result.L1_1 = polynomial.y.scale(0.977204);
  74855. result.L10 = polynomial.z.scale(0.977204);
  74856. result.L11 = polynomial.x.scale(0.977204);
  74857. result.L2_2 = polynomial.xy.scale(1.16538);
  74858. result.L2_1 = polynomial.yz.scale(1.16538);
  74859. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74860. result.L21 = polynomial.zx.scale(1.16538);
  74861. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74862. result.scale(Math.PI);
  74863. return result;
  74864. };
  74865. return SphericalHarmonics;
  74866. }());
  74867. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74868. })(BABYLON || (BABYLON = {}));
  74869. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74870. "use strict";
  74871. var BABYLON;
  74872. (function (BABYLON) {
  74873. var FileFaceOrientation = /** @class */ (function () {
  74874. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74875. this.name = name;
  74876. this.worldAxisForNormal = worldAxisForNormal;
  74877. this.worldAxisForFileX = worldAxisForFileX;
  74878. this.worldAxisForFileY = worldAxisForFileY;
  74879. }
  74880. return FileFaceOrientation;
  74881. }());
  74882. ;
  74883. /**
  74884. * Helper class dealing with the extraction of spherical polynomial dataArray
  74885. * from a cube map.
  74886. */
  74887. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74888. function CubeMapToSphericalPolynomialTools() {
  74889. }
  74890. /**
  74891. * Converts a texture to the according Spherical Polynomial data.
  74892. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74893. *
  74894. * @param texture The texture to extract the information from.
  74895. * @return The Spherical Polynomial data.
  74896. */
  74897. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74898. if (!texture.isCube) {
  74899. // Only supports cube Textures currently.
  74900. return null;
  74901. }
  74902. var size = texture.getSize().width;
  74903. var right = texture.readPixels(0);
  74904. var left = texture.readPixels(1);
  74905. var up;
  74906. var down;
  74907. if (texture.isRenderTarget) {
  74908. up = texture.readPixels(3);
  74909. down = texture.readPixels(2);
  74910. }
  74911. else {
  74912. up = texture.readPixels(2);
  74913. down = texture.readPixels(3);
  74914. }
  74915. var front = texture.readPixels(4);
  74916. var back = texture.readPixels(5);
  74917. var gammaSpace = texture.gammaSpace;
  74918. // Always read as RGBA.
  74919. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74920. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74921. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74922. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74923. }
  74924. var cubeInfo = {
  74925. size: size,
  74926. right: right,
  74927. left: left,
  74928. up: up,
  74929. down: down,
  74930. front: front,
  74931. back: back,
  74932. format: format,
  74933. type: type,
  74934. gammaSpace: gammaSpace,
  74935. };
  74936. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74937. };
  74938. /**
  74939. * Converts a cubemap to the according Spherical Polynomial data.
  74940. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74941. *
  74942. * @param cubeInfo The Cube map to extract the information from.
  74943. * @return The Spherical Polynomial data.
  74944. */
  74945. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74946. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74947. var totalSolidAngle = 0.0;
  74948. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74949. var du = 2.0 / cubeInfo.size;
  74950. var dv = du;
  74951. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74952. var minUV = du * 0.5 - 1.0;
  74953. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74954. var fileFace = this.FileFaces[faceIndex];
  74955. var dataArray = cubeInfo[fileFace.name];
  74956. var v = minUV;
  74957. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74958. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74959. // Because SP is still linear, so summation is fine in that basis.
  74960. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74961. for (var y = 0; y < cubeInfo.size; y++) {
  74962. var u = minUV;
  74963. for (var x = 0; x < cubeInfo.size; x++) {
  74964. // World direction (not normalised)
  74965. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74966. worldDirection.normalize();
  74967. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74968. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74969. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74970. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74971. // Handle Integer types.
  74972. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74973. r /= 255;
  74974. g /= 255;
  74975. b /= 255;
  74976. }
  74977. // Handle Gamma space textures.
  74978. if (cubeInfo.gammaSpace) {
  74979. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74980. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74981. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74982. }
  74983. var color = new BABYLON.Color3(r, g, b);
  74984. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74985. totalSolidAngle += deltaSolidAngle;
  74986. u += du;
  74987. }
  74988. v += dv;
  74989. }
  74990. }
  74991. // Solid angle for entire sphere is 4*pi
  74992. var sphereSolidAngle = 4.0 * Math.PI;
  74993. // Adjust the solid angle to allow for how many faces we processed.
  74994. var facesProcessed = 6.0;
  74995. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74996. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74997. // This is needed because the numerical integration over the cube uses a
  74998. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74999. // and also to compensate for accumulative error due to float precision in the summation.
  75000. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  75001. sphericalHarmonics.scale(correctionFactor);
  75002. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  75003. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  75004. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  75005. };
  75006. CubeMapToSphericalPolynomialTools.FileFaces = [
  75007. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  75008. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  75009. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  75010. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  75011. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  75012. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  75013. ];
  75014. return CubeMapToSphericalPolynomialTools;
  75015. }());
  75016. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  75017. })(BABYLON || (BABYLON = {}));
  75018. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  75019. "use strict";
  75020. var BABYLON;
  75021. (function (BABYLON) {
  75022. /**
  75023. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  75024. */
  75025. var PanoramaToCubeMapTools = /** @class */ (function () {
  75026. function PanoramaToCubeMapTools() {
  75027. }
  75028. /**
  75029. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  75030. *
  75031. * @param float32Array The source data.
  75032. * @param inputWidth The width of the input panorama.
  75033. * @param inputhHeight The height of the input panorama.
  75034. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  75035. * @return The cubemap data
  75036. */
  75037. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  75038. if (!float32Array) {
  75039. throw "ConvertPanoramaToCubemap: input cannot be null";
  75040. }
  75041. if (float32Array.length != inputWidth * inputHeight * 3) {
  75042. throw "ConvertPanoramaToCubemap: input size is wrong";
  75043. }
  75044. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  75045. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  75046. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  75047. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  75048. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  75049. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  75050. return {
  75051. front: textureFront,
  75052. back: textureBack,
  75053. left: textureLeft,
  75054. right: textureRight,
  75055. up: textureUp,
  75056. down: textureDown,
  75057. size: size,
  75058. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  75059. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  75060. gammaSpace: false,
  75061. };
  75062. };
  75063. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  75064. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  75065. var textureArray = new Float32Array(buffer);
  75066. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  75067. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  75068. var dy = 1 / texSize;
  75069. var fy = 0;
  75070. for (var y = 0; y < texSize; y++) {
  75071. var xv1 = faceData[0];
  75072. var xv2 = faceData[2];
  75073. for (var x = 0; x < texSize; x++) {
  75074. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  75075. v.normalize();
  75076. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  75077. // 3 channels per pixels
  75078. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  75079. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  75080. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  75081. xv1 = xv1.add(rotDX1);
  75082. xv2 = xv2.add(rotDX2);
  75083. }
  75084. fy += dy;
  75085. }
  75086. return textureArray;
  75087. };
  75088. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  75089. var theta = Math.atan2(vDir.z, vDir.x);
  75090. var phi = Math.acos(vDir.y);
  75091. while (theta < -Math.PI)
  75092. theta += 2 * Math.PI;
  75093. while (theta > Math.PI)
  75094. theta -= 2 * Math.PI;
  75095. var dx = theta / Math.PI;
  75096. var dy = phi / Math.PI;
  75097. // recenter.
  75098. dx = dx * 0.5 + 0.5;
  75099. var px = Math.round(dx * inputWidth);
  75100. if (px < 0)
  75101. px = 0;
  75102. else if (px >= inputWidth)
  75103. px = inputWidth - 1;
  75104. var py = Math.round(dy * inputHeight);
  75105. if (py < 0)
  75106. py = 0;
  75107. else if (py >= inputHeight)
  75108. py = inputHeight - 1;
  75109. var inputY = (inputHeight - py - 1);
  75110. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  75111. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  75112. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  75113. return {
  75114. r: r,
  75115. g: g,
  75116. b: b
  75117. };
  75118. };
  75119. PanoramaToCubeMapTools.FACE_FRONT = [
  75120. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75121. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75122. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75123. new BABYLON.Vector3(1.0, 1.0, -1.0)
  75124. ];
  75125. PanoramaToCubeMapTools.FACE_BACK = [
  75126. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75127. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75128. new BABYLON.Vector3(1.0, 1.0, 1.0),
  75129. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  75130. ];
  75131. PanoramaToCubeMapTools.FACE_RIGHT = [
  75132. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75133. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75134. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75135. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75136. ];
  75137. PanoramaToCubeMapTools.FACE_LEFT = [
  75138. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75139. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75140. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75141. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  75142. ];
  75143. PanoramaToCubeMapTools.FACE_DOWN = [
  75144. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75145. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75146. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75147. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75148. ];
  75149. PanoramaToCubeMapTools.FACE_UP = [
  75150. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75151. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75152. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75153. new BABYLON.Vector3(1.0, -1.0, -1.0)
  75154. ];
  75155. return PanoramaToCubeMapTools;
  75156. }());
  75157. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  75158. })(BABYLON || (BABYLON = {}));
  75159. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  75160. "use strict";
  75161. var BABYLON;
  75162. (function (BABYLON) {
  75163. ;
  75164. /**
  75165. * This groups tools to convert HDR texture to native colors array.
  75166. */
  75167. var HDRTools = /** @class */ (function () {
  75168. function HDRTools() {
  75169. }
  75170. HDRTools.Ldexp = function (mantissa, exponent) {
  75171. if (exponent > 1023) {
  75172. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  75173. }
  75174. if (exponent < -1074) {
  75175. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  75176. }
  75177. return mantissa * Math.pow(2, exponent);
  75178. };
  75179. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  75180. if (exponent > 0) {
  75181. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  75182. float32array[index + 0] = red * exponent;
  75183. float32array[index + 1] = green * exponent;
  75184. float32array[index + 2] = blue * exponent;
  75185. }
  75186. else {
  75187. float32array[index + 0] = 0;
  75188. float32array[index + 1] = 0;
  75189. float32array[index + 2] = 0;
  75190. }
  75191. };
  75192. HDRTools.readStringLine = function (uint8array, startIndex) {
  75193. var line = "";
  75194. var character = "";
  75195. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  75196. character = String.fromCharCode(uint8array[i]);
  75197. if (character == "\n") {
  75198. break;
  75199. }
  75200. line += character;
  75201. }
  75202. return line;
  75203. };
  75204. /**
  75205. * Reads header information from an RGBE texture stored in a native array.
  75206. * More information on this format are available here:
  75207. * https://en.wikipedia.org/wiki/RGBE_image_format
  75208. *
  75209. * @param uint8array The binary file stored in native array.
  75210. * @return The header information.
  75211. */
  75212. HDRTools.RGBE_ReadHeader = function (uint8array) {
  75213. var height = 0;
  75214. var width = 0;
  75215. var line = this.readStringLine(uint8array, 0);
  75216. if (line[0] != '#' || line[1] != '?') {
  75217. throw "Bad HDR Format.";
  75218. }
  75219. var endOfHeader = false;
  75220. var findFormat = false;
  75221. var lineIndex = 0;
  75222. do {
  75223. lineIndex += (line.length + 1);
  75224. line = this.readStringLine(uint8array, lineIndex);
  75225. if (line == "FORMAT=32-bit_rle_rgbe") {
  75226. findFormat = true;
  75227. }
  75228. else if (line.length == 0) {
  75229. endOfHeader = true;
  75230. }
  75231. } while (!endOfHeader);
  75232. if (!findFormat) {
  75233. throw "HDR Bad header format, unsupported FORMAT";
  75234. }
  75235. lineIndex += (line.length + 1);
  75236. line = this.readStringLine(uint8array, lineIndex);
  75237. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75238. var match = sizeRegexp.exec(line);
  75239. // TODO. Support +Y and -X if needed.
  75240. if (!match || match.length < 3) {
  75241. throw "HDR Bad header format, no size";
  75242. }
  75243. width = parseInt(match[2]);
  75244. height = parseInt(match[1]);
  75245. if (width < 8 || width > 0x7fff) {
  75246. throw "HDR Bad header format, unsupported size";
  75247. }
  75248. lineIndex += (line.length + 1);
  75249. return {
  75250. height: height,
  75251. width: width,
  75252. dataPosition: lineIndex
  75253. };
  75254. };
  75255. /**
  75256. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75257. * This RGBE texture needs to store the information as a panorama.
  75258. *
  75259. * More information on this format are available here:
  75260. * https://en.wikipedia.org/wiki/RGBE_image_format
  75261. *
  75262. * @param buffer The binary file stored in an array buffer.
  75263. * @param size The expected size of the extracted cubemap.
  75264. * @return The Cube Map information.
  75265. */
  75266. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75267. var uint8array = new Uint8Array(buffer);
  75268. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75269. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75270. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75271. return cubeMapData;
  75272. };
  75273. /**
  75274. * Returns the pixels data extracted from an RGBE texture.
  75275. * This pixels will be stored left to right up to down in the R G B order in one array.
  75276. *
  75277. * More information on this format are available here:
  75278. * https://en.wikipedia.org/wiki/RGBE_image_format
  75279. *
  75280. * @param uint8array The binary file stored in an array buffer.
  75281. * @param hdrInfo The header information of the file.
  75282. * @return The pixels data in RGB right to left up to down order.
  75283. */
  75284. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75285. // Keep for multi format supports.
  75286. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75287. };
  75288. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75289. var num_scanlines = hdrInfo.height;
  75290. var scanline_width = hdrInfo.width;
  75291. var a, b, c, d, count;
  75292. var dataIndex = hdrInfo.dataPosition;
  75293. var index = 0, endIndex = 0, i = 0;
  75294. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75295. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75296. // 3 channels of 4 bytes per pixel in float.
  75297. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75298. var resultArray = new Float32Array(resultBuffer);
  75299. // read in each successive scanline
  75300. while (num_scanlines > 0) {
  75301. a = uint8array[dataIndex++];
  75302. b = uint8array[dataIndex++];
  75303. c = uint8array[dataIndex++];
  75304. d = uint8array[dataIndex++];
  75305. if (a != 2 || b != 2 || (c & 0x80)) {
  75306. // this file is not run length encoded
  75307. throw "HDR Bad header format, not RLE";
  75308. }
  75309. if (((c << 8) | d) != scanline_width) {
  75310. throw "HDR Bad header format, wrong scan line width";
  75311. }
  75312. index = 0;
  75313. // read each of the four channels for the scanline into the buffer
  75314. for (i = 0; i < 4; i++) {
  75315. endIndex = (i + 1) * scanline_width;
  75316. while (index < endIndex) {
  75317. a = uint8array[dataIndex++];
  75318. b = uint8array[dataIndex++];
  75319. if (a > 128) {
  75320. // a run of the same value
  75321. count = a - 128;
  75322. if ((count == 0) || (count > endIndex - index)) {
  75323. throw "HDR Bad Format, bad scanline data (run)";
  75324. }
  75325. while (count-- > 0) {
  75326. scanLineArray[index++] = b;
  75327. }
  75328. }
  75329. else {
  75330. // a non-run
  75331. count = a;
  75332. if ((count == 0) || (count > endIndex - index)) {
  75333. throw "HDR Bad Format, bad scanline data (non-run)";
  75334. }
  75335. scanLineArray[index++] = b;
  75336. if (--count > 0) {
  75337. for (var j = 0; j < count; j++) {
  75338. scanLineArray[index++] = uint8array[dataIndex++];
  75339. }
  75340. }
  75341. }
  75342. }
  75343. }
  75344. // now convert data from buffer into floats
  75345. for (i = 0; i < scanline_width; i++) {
  75346. a = scanLineArray[i];
  75347. b = scanLineArray[i + scanline_width];
  75348. c = scanLineArray[i + 2 * scanline_width];
  75349. d = scanLineArray[i + 3 * scanline_width];
  75350. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75351. }
  75352. num_scanlines--;
  75353. }
  75354. return resultArray;
  75355. };
  75356. return HDRTools;
  75357. }());
  75358. BABYLON.HDRTools = HDRTools;
  75359. })(BABYLON || (BABYLON = {}));
  75360. //# sourceMappingURL=babylon.hdr.js.map
  75361. "use strict";
  75362. var BABYLON;
  75363. (function (BABYLON) {
  75364. /**
  75365. * This represents a texture coming from an HDR input.
  75366. *
  75367. * The only supported format is currently panorama picture stored in RGBE format.
  75368. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75369. */
  75370. var HDRCubeTexture = /** @class */ (function (_super) {
  75371. __extends(HDRCubeTexture, _super);
  75372. /**
  75373. * Instantiates an HDRTexture from the following parameters.
  75374. *
  75375. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75376. * @param scene The scene the texture will be used in
  75377. * @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.
  75378. * @param noMipmap Forces to not generate the mipmap if true
  75379. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75380. * @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)
  75381. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75382. */
  75383. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75384. if (noMipmap === void 0) { noMipmap = false; }
  75385. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75386. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75387. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75388. if (onLoad === void 0) { onLoad = null; }
  75389. if (onError === void 0) { onError = null; }
  75390. var _this = _super.call(this, scene) || this;
  75391. _this._useInGammaSpace = false;
  75392. _this._generateHarmonics = true;
  75393. _this._isBABYLONPreprocessed = false;
  75394. _this._onLoad = null;
  75395. _this._onError = null;
  75396. /**
  75397. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75398. */
  75399. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75400. /**
  75401. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75402. * This is usefull at run time to apply the good shader.
  75403. */
  75404. _this.isPMREM = false;
  75405. _this._isBlocking = true;
  75406. /**
  75407. * Gets or sets the center of the bounding box associated with the cube texture
  75408. * It must define where the camera used to render the texture was set
  75409. */
  75410. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75411. if (!url) {
  75412. return _this;
  75413. }
  75414. _this.name = url;
  75415. _this.url = url;
  75416. _this.hasAlpha = false;
  75417. _this.isCube = true;
  75418. _this._textureMatrix = BABYLON.Matrix.Identity();
  75419. _this._onLoad = onLoad;
  75420. _this._onError = onError;
  75421. _this.gammaSpace = false;
  75422. var caps = scene.getEngine().getCaps();
  75423. if (size) {
  75424. _this._isBABYLONPreprocessed = false;
  75425. _this._noMipmap = noMipmap;
  75426. _this._size = size;
  75427. _this._useInGammaSpace = useInGammaSpace;
  75428. _this._usePMREMGenerator = usePMREMGenerator &&
  75429. caps.textureLOD &&
  75430. caps.textureFloat &&
  75431. !_this._useInGammaSpace;
  75432. }
  75433. else {
  75434. _this._isBABYLONPreprocessed = true;
  75435. _this._noMipmap = false;
  75436. _this._useInGammaSpace = false;
  75437. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75438. !_this._useInGammaSpace;
  75439. }
  75440. _this.isPMREM = _this._usePMREMGenerator;
  75441. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75442. if (!_this._texture) {
  75443. if (!scene.useDelayedTextureLoading) {
  75444. _this.loadTexture();
  75445. }
  75446. else {
  75447. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75448. }
  75449. }
  75450. return _this;
  75451. }
  75452. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75453. /**
  75454. * Gets wether or not the texture is blocking during loading.
  75455. */
  75456. get: function () {
  75457. return this._isBlocking;
  75458. },
  75459. /**
  75460. * Sets wether or not the texture is blocking during loading.
  75461. */
  75462. set: function (value) {
  75463. this._isBlocking = value;
  75464. },
  75465. enumerable: true,
  75466. configurable: true
  75467. });
  75468. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75469. get: function () {
  75470. return this._boundingBoxSize;
  75471. },
  75472. /**
  75473. * Gets or sets the size of the bounding box associated with the cube texture
  75474. * When defined, the cubemap will switch to local mode
  75475. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75476. * @example https://www.babylonjs-playground.com/#RNASML
  75477. */
  75478. set: function (value) {
  75479. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75480. return;
  75481. }
  75482. this._boundingBoxSize = value;
  75483. var scene = this.getScene();
  75484. if (scene) {
  75485. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75486. }
  75487. },
  75488. enumerable: true,
  75489. configurable: true
  75490. });
  75491. /**
  75492. * Occurs when the file is a preprocessed .babylon.hdr file.
  75493. */
  75494. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75495. var _this = this;
  75496. var mipLevels = 0;
  75497. var floatArrayView = null;
  75498. var scene = this.getScene();
  75499. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75500. var mips = new Array();
  75501. if (!floatArrayView) {
  75502. return mips;
  75503. }
  75504. var startIndex = 30;
  75505. for (var level = 0; level < mipLevels; level++) {
  75506. mips.push([]);
  75507. // Fill each pixel of the mip level.
  75508. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75509. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75510. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75511. mips[level].push(faceData);
  75512. startIndex += faceSize;
  75513. }
  75514. }
  75515. return mips;
  75516. } : null;
  75517. var callback = function (buffer) {
  75518. var scene = _this.getScene();
  75519. if (!scene) {
  75520. return null;
  75521. }
  75522. // Create Native Array Views
  75523. var intArrayView = new Int32Array(buffer);
  75524. floatArrayView = new Float32Array(buffer);
  75525. // Fill header.
  75526. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75527. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75528. // Update Texture Information.
  75529. if (!_this._texture) {
  75530. return null;
  75531. }
  75532. _this._texture.updateSize(_this._size, _this._size);
  75533. // Fill polynomial information.
  75534. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75535. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75536. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75537. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75538. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75539. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75540. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75541. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75542. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75543. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75544. _this.sphericalPolynomial = sphericalPolynomial;
  75545. // Fill pixel data.
  75546. mipLevels = intArrayView[29]; // Number of mip levels.
  75547. var startIndex = 30;
  75548. var data = [];
  75549. var faceSize = Math.pow(_this._size, 2) * 3;
  75550. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75551. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75552. startIndex += faceSize;
  75553. }
  75554. var results = [];
  75555. var byteArray = null;
  75556. // Push each faces.
  75557. for (var k = 0; k < 6; k++) {
  75558. var dataFace = null;
  75559. // To be deprecated.
  75560. if (version === 1) {
  75561. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75562. dataFace = data[j];
  75563. }
  75564. // If special cases.
  75565. if (!mipmapGenerator && dataFace) {
  75566. if (!scene.getEngine().getCaps().textureFloat) {
  75567. // 3 channels of 1 bytes per pixel in bytes.
  75568. var byteBuffer = new ArrayBuffer(faceSize);
  75569. byteArray = new Uint8Array(byteBuffer);
  75570. }
  75571. for (var i = 0; i < _this._size * _this._size; i++) {
  75572. // Put in gamma space if requested.
  75573. if (_this._useInGammaSpace) {
  75574. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75575. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75576. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75577. }
  75578. // Convert to int texture for fallback.
  75579. if (byteArray) {
  75580. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75581. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75582. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75583. // May use luminance instead if the result is not accurate.
  75584. var max = Math.max(Math.max(r, g), b);
  75585. if (max > 255) {
  75586. var scale = 255 / max;
  75587. r *= scale;
  75588. g *= scale;
  75589. b *= scale;
  75590. }
  75591. byteArray[(i * 3) + 0] = r;
  75592. byteArray[(i * 3) + 1] = g;
  75593. byteArray[(i * 3) + 2] = b;
  75594. }
  75595. }
  75596. }
  75597. // Fill the array accordingly.
  75598. if (byteArray) {
  75599. results.push(byteArray);
  75600. }
  75601. else {
  75602. results.push(dataFace);
  75603. }
  75604. }
  75605. return results;
  75606. };
  75607. if (scene) {
  75608. 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);
  75609. }
  75610. };
  75611. /**
  75612. * Occurs when the file is raw .hdr file.
  75613. */
  75614. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75615. var _this = this;
  75616. var callback = function (buffer) {
  75617. var scene = _this.getScene();
  75618. if (!scene) {
  75619. return null;
  75620. }
  75621. // Extract the raw linear data.
  75622. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75623. // Generate harmonics if needed.
  75624. if (_this._generateHarmonics) {
  75625. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75626. _this.sphericalPolynomial = sphericalPolynomial;
  75627. }
  75628. var results = [];
  75629. var byteArray = null;
  75630. // Push each faces.
  75631. for (var j = 0; j < 6; j++) {
  75632. // Create uintarray fallback.
  75633. if (!scene.getEngine().getCaps().textureFloat) {
  75634. // 3 channels of 1 bytes per pixel in bytes.
  75635. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75636. byteArray = new Uint8Array(byteBuffer);
  75637. }
  75638. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75639. // If special cases.
  75640. if (_this._useInGammaSpace || byteArray) {
  75641. for (var i = 0; i < _this._size * _this._size; i++) {
  75642. // Put in gamma space if requested.
  75643. if (_this._useInGammaSpace) {
  75644. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75645. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75646. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75647. }
  75648. // Convert to int texture for fallback.
  75649. if (byteArray) {
  75650. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75651. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75652. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75653. // May use luminance instead if the result is not accurate.
  75654. var max = Math.max(Math.max(r, g), b);
  75655. if (max > 255) {
  75656. var scale = 255 / max;
  75657. r *= scale;
  75658. g *= scale;
  75659. b *= scale;
  75660. }
  75661. byteArray[(i * 3) + 0] = r;
  75662. byteArray[(i * 3) + 1] = g;
  75663. byteArray[(i * 3) + 2] = b;
  75664. }
  75665. }
  75666. }
  75667. if (byteArray) {
  75668. results.push(byteArray);
  75669. }
  75670. else {
  75671. results.push(dataFace);
  75672. }
  75673. }
  75674. return results;
  75675. };
  75676. var mipmapGenerator = null;
  75677. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75678. // if (!this._noMipmap &&
  75679. // this._usePMREMGenerator) {
  75680. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75681. // // Custom setup of the generator matching with the PBR shader values.
  75682. // var generator = new BABYLON.PMREMGenerator(data,
  75683. // this._size,
  75684. // this._size,
  75685. // 0,
  75686. // 3,
  75687. // this.getScene().getEngine().getCaps().textureFloat,
  75688. // 2048,
  75689. // 0.25,
  75690. // false,
  75691. // true);
  75692. // return generator.filterCubeMap();
  75693. // };
  75694. // }
  75695. var scene = this.getScene();
  75696. if (scene) {
  75697. 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);
  75698. }
  75699. };
  75700. /**
  75701. * Starts the loading process of the texture.
  75702. */
  75703. HDRCubeTexture.prototype.loadTexture = function () {
  75704. if (this._isBABYLONPreprocessed) {
  75705. this.loadBabylonTexture();
  75706. }
  75707. else {
  75708. this.loadHDRTexture();
  75709. }
  75710. };
  75711. HDRCubeTexture.prototype.clone = function () {
  75712. var scene = this.getScene();
  75713. if (!scene) {
  75714. return this;
  75715. }
  75716. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75717. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75718. // Base texture
  75719. newTexture.level = this.level;
  75720. newTexture.wrapU = this.wrapU;
  75721. newTexture.wrapV = this.wrapV;
  75722. newTexture.coordinatesIndex = this.coordinatesIndex;
  75723. newTexture.coordinatesMode = this.coordinatesMode;
  75724. return newTexture;
  75725. };
  75726. // Methods
  75727. HDRCubeTexture.prototype.delayLoad = function () {
  75728. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75729. return;
  75730. }
  75731. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75732. this._texture = this._getFromCache(this.url, this._noMipmap);
  75733. if (!this._texture) {
  75734. this.loadTexture();
  75735. }
  75736. };
  75737. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75738. return this._textureMatrix;
  75739. };
  75740. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75741. this._textureMatrix = value;
  75742. };
  75743. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75744. var texture = null;
  75745. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75746. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75747. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75748. texture.name = parsedTexture.name;
  75749. texture.hasAlpha = parsedTexture.hasAlpha;
  75750. texture.level = parsedTexture.level;
  75751. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75752. texture.isBlocking = parsedTexture.isBlocking;
  75753. }
  75754. if (texture) {
  75755. if (parsedTexture.boundingBoxPosition) {
  75756. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75757. }
  75758. if (parsedTexture.boundingBoxSize) {
  75759. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75760. }
  75761. }
  75762. return texture;
  75763. };
  75764. HDRCubeTexture.prototype.serialize = function () {
  75765. if (!this.name) {
  75766. return null;
  75767. }
  75768. var serializationObject = {};
  75769. serializationObject.name = this.name;
  75770. serializationObject.hasAlpha = this.hasAlpha;
  75771. serializationObject.isCube = true;
  75772. serializationObject.level = this.level;
  75773. serializationObject.size = this._size;
  75774. serializationObject.coordinatesMode = this.coordinatesMode;
  75775. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75776. serializationObject.generateHarmonics = this._generateHarmonics;
  75777. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75778. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75779. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75780. serializationObject.noMipmap = this._noMipmap;
  75781. serializationObject.isBlocking = this._isBlocking;
  75782. return serializationObject;
  75783. };
  75784. /**
  75785. * Saves as a file the data contained in the texture in a binary format.
  75786. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75787. * as the spherical used in the lighting.
  75788. * @param url The HDR file url.
  75789. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75790. * @param onError Method called if any error happens during download.
  75791. * @return The packed binary data.
  75792. */
  75793. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75794. if (onError === void 0) { onError = null; }
  75795. var callback = function (buffer) {
  75796. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75797. // Returns a URL you can use as a href.
  75798. var objUrl = window.URL.createObjectURL(data);
  75799. // Simulates a link to it and click to dowload.
  75800. var a = document.createElement("a");
  75801. document.body.appendChild(a);
  75802. a.style.display = "none";
  75803. a.href = objUrl;
  75804. a.download = "envmap.babylon.hdr";
  75805. a.click();
  75806. };
  75807. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75808. };
  75809. /**
  75810. * Serializes the data contained in the texture in a binary format.
  75811. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75812. * as the spherical used in the lighting.
  75813. * @param url The HDR file url.
  75814. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75815. * @param onError Method called if any error happens during download.
  75816. * @return The packed binary data.
  75817. */
  75818. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75819. if (onError === void 0) { onError = null; }
  75820. // Needs the url tho create the texture.
  75821. if (!url) {
  75822. return;
  75823. }
  75824. // Check Power of two size.
  75825. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75826. return;
  75827. }
  75828. // Coming Back in 3.x.
  75829. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75830. };
  75831. HDRCubeTexture._facesMapping = [
  75832. "right",
  75833. "left",
  75834. "up",
  75835. "down",
  75836. "front",
  75837. "back"
  75838. ];
  75839. return HDRCubeTexture;
  75840. }(BABYLON.BaseTexture));
  75841. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75842. })(BABYLON || (BABYLON = {}));
  75843. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75844. "use strict";
  75845. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75846. // Huge respect for a such great lib.
  75847. // Earcut license:
  75848. // Copyright (c) 2016, Mapbox
  75849. //
  75850. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75851. // with or without fee is hereby granted, provided that the above copyright notice
  75852. // and this permission notice appear in all copies.
  75853. //
  75854. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75855. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75856. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75857. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75858. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75859. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75860. // THIS SOFTWARE.
  75861. var Earcut;
  75862. (function (Earcut) {
  75863. /**
  75864. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75865. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75866. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75867. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75868. */
  75869. function earcut(data, holeIndices, dim) {
  75870. dim = dim || 2;
  75871. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75872. if (!outerNode)
  75873. return triangles;
  75874. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75875. if (hasHoles)
  75876. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75877. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75878. if (data.length > 80 * dim) {
  75879. minX = maxX = data[0];
  75880. minY = maxY = data[1];
  75881. for (var i = dim; i < outerLen; i += dim) {
  75882. x = data[i];
  75883. y = data[i + 1];
  75884. if (x < minX)
  75885. minX = x;
  75886. if (y < minY)
  75887. minY = y;
  75888. if (x > maxX)
  75889. maxX = x;
  75890. if (y > maxY)
  75891. maxY = y;
  75892. }
  75893. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75894. size = Math.max(maxX - minX, maxY - minY);
  75895. }
  75896. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75897. return triangles;
  75898. }
  75899. Earcut.earcut = earcut;
  75900. var Node = /** @class */ (function () {
  75901. function Node(i, x, y) {
  75902. this.i = i;
  75903. this.x = x;
  75904. this.y = y;
  75905. this.prev = null;
  75906. this.next = null;
  75907. this.z = null;
  75908. this.prevZ = null;
  75909. this.nextZ = null;
  75910. this.steiner = false;
  75911. }
  75912. return Node;
  75913. }());
  75914. // create a circular doubly linked list from polygon points in the specified winding order
  75915. function linkedList(data, start, end, dim, clockwise) {
  75916. var i, last = null;
  75917. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75918. for (i = start; i < end; i += dim)
  75919. last = insertNode(i, data[i], data[i + 1], last);
  75920. }
  75921. else {
  75922. for (i = end - dim; i >= start; i -= dim)
  75923. last = insertNode(i, data[i], data[i + 1], last);
  75924. }
  75925. if (last && equals(last, last.next)) {
  75926. removeNode(last);
  75927. last = last.next;
  75928. }
  75929. return last;
  75930. }
  75931. // eliminate colinear or duplicate points
  75932. function filterPoints(start, end) {
  75933. if (!start)
  75934. return start;
  75935. if (!end)
  75936. end = start;
  75937. var p = start, again;
  75938. do {
  75939. again = false;
  75940. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75941. removeNode(p);
  75942. p = end = p.prev;
  75943. if (p === p.next)
  75944. return undefined;
  75945. again = true;
  75946. }
  75947. else {
  75948. p = p.next;
  75949. }
  75950. } while (again || p !== end);
  75951. return end;
  75952. }
  75953. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75954. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75955. if (!ear)
  75956. return;
  75957. // interlink polygon nodes in z-order
  75958. if (!pass && size)
  75959. indexCurve(ear, minX, minY, size);
  75960. var stop = ear, prev, next;
  75961. // iterate through ears, slicing them one by one
  75962. while (ear.prev !== ear.next) {
  75963. prev = ear.prev;
  75964. next = ear.next;
  75965. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75966. // cut off the triangle
  75967. triangles.push(prev.i / dim);
  75968. triangles.push(ear.i / dim);
  75969. triangles.push(next.i / dim);
  75970. removeNode(ear);
  75971. // skipping the next vertice leads to less sliver triangles
  75972. ear = next.next;
  75973. stop = next.next;
  75974. continue;
  75975. }
  75976. ear = next;
  75977. // if we looped through the whole remaining polygon and can't find any more ears
  75978. if (ear === stop) {
  75979. // try filtering points and slicing again
  75980. if (!pass) {
  75981. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75982. // if this didn't work, try curing all small self-intersections locally
  75983. }
  75984. else if (pass === 1) {
  75985. ear = cureLocalIntersections(ear, triangles, dim);
  75986. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75987. // as a last resort, try splitting the remaining polygon into two
  75988. }
  75989. else if (pass === 2) {
  75990. splitEarcut(ear, triangles, dim, minX, minY, size);
  75991. }
  75992. break;
  75993. }
  75994. }
  75995. }
  75996. // check whether a polygon node forms a valid ear with adjacent nodes
  75997. function isEar(ear) {
  75998. var a = ear.prev, b = ear, c = ear.next;
  75999. if (area(a, b, c) >= 0)
  76000. return false; // reflex, can't be an ear
  76001. // now make sure we don't have other points inside the potential ear
  76002. var p = ear.next.next;
  76003. while (p !== ear.prev) {
  76004. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  76005. area(p.prev, p, p.next) >= 0)
  76006. return false;
  76007. p = p.next;
  76008. }
  76009. return true;
  76010. }
  76011. function isEarHashed(ear, minX, minY, size) {
  76012. var a = ear.prev, b = ear, c = ear.next;
  76013. if (area(a, b, c) >= 0)
  76014. return false; // reflex, can't be an ear
  76015. // triangle bbox; min & max are calculated like this for speed
  76016. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  76017. // z-order range for the current triangle bbox;
  76018. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  76019. // first look for points inside the triangle in increasing z-order
  76020. var p = ear.nextZ;
  76021. while (p && p.z <= maxZ) {
  76022. if (p !== ear.prev &&
  76023. p !== ear.next &&
  76024. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  76025. area(p.prev, p, p.next) >= 0)
  76026. return false;
  76027. p = p.nextZ;
  76028. }
  76029. // then look for points in decreasing z-order
  76030. p = ear.prevZ;
  76031. while (p && p.z >= minZ) {
  76032. if (p !== ear.prev &&
  76033. p !== ear.next &&
  76034. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  76035. area(p.prev, p, p.next) >= 0)
  76036. return false;
  76037. p = p.prevZ;
  76038. }
  76039. return true;
  76040. }
  76041. // go through all polygon nodes and cure small local self-intersections
  76042. function cureLocalIntersections(start, triangles, dim) {
  76043. var p = start;
  76044. do {
  76045. var a = p.prev, b = p.next.next;
  76046. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  76047. triangles.push(a.i / dim);
  76048. triangles.push(p.i / dim);
  76049. triangles.push(b.i / dim);
  76050. // remove two nodes involved
  76051. removeNode(p);
  76052. removeNode(p.next);
  76053. p = start = b;
  76054. }
  76055. p = p.next;
  76056. } while (p !== start);
  76057. return p;
  76058. }
  76059. // try splitting polygon into two and triangulate them independently
  76060. function splitEarcut(start, triangles, dim, minX, minY, size) {
  76061. // look for a valid diagonal that divides the polygon into two
  76062. var a = start;
  76063. do {
  76064. var b = a.next.next;
  76065. while (b !== a.prev) {
  76066. if (a.i !== b.i && isValidDiagonal(a, b)) {
  76067. // split the polygon in two by the diagonal
  76068. var c = splitPolygon(a, b);
  76069. // filter colinear points around the cuts
  76070. a = filterPoints(a, a.next);
  76071. c = filterPoints(c, c.next);
  76072. // run earcut on each half
  76073. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  76074. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  76075. return;
  76076. }
  76077. b = b.next;
  76078. }
  76079. a = a.next;
  76080. } while (a !== start);
  76081. }
  76082. // link every hole into the outer loop, producing a single-ring polygon without holes
  76083. function eliminateHoles(data, holeIndices, outerNode, dim) {
  76084. var queue = [], i, len, start, end, list;
  76085. for (i = 0, len = holeIndices.length; i < len; i++) {
  76086. start = holeIndices[i] * dim;
  76087. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76088. list = linkedList(data, start, end, dim, false);
  76089. if (list === list.next)
  76090. list.steiner = true;
  76091. queue.push(getLeftmost(list));
  76092. }
  76093. queue.sort(compareX);
  76094. // process holes from left to right
  76095. for (i = 0; i < queue.length; i++) {
  76096. eliminateHole(queue[i], outerNode);
  76097. outerNode = filterPoints(outerNode, outerNode.next);
  76098. }
  76099. return outerNode;
  76100. }
  76101. function compareX(a, b) {
  76102. return a.x - b.x;
  76103. }
  76104. // find a bridge between vertices that connects hole with an outer ring and and link it
  76105. function eliminateHole(hole, outerNode) {
  76106. outerNode = findHoleBridge(hole, outerNode);
  76107. if (outerNode) {
  76108. var b = splitPolygon(outerNode, hole);
  76109. filterPoints(b, b.next);
  76110. }
  76111. }
  76112. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  76113. function findHoleBridge(hole, outerNode) {
  76114. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  76115. // find a segment intersected by a ray from the hole's leftmost point to the left;
  76116. // segment's endpoint with lesser x will be potential connection point
  76117. do {
  76118. if (hy <= p.y && hy >= p.next.y) {
  76119. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  76120. if (x <= hx && x > qx) {
  76121. qx = x;
  76122. if (x === hx) {
  76123. if (hy === p.y)
  76124. return p;
  76125. if (hy === p.next.y)
  76126. return p.next;
  76127. }
  76128. m = p.x < p.next.x ? p : p.next;
  76129. }
  76130. }
  76131. p = p.next;
  76132. } while (p !== outerNode);
  76133. if (!m)
  76134. return null;
  76135. if (hx === qx)
  76136. return m.prev; // hole touches outer segment; pick lower endpoint
  76137. // look for points inside the triangle of hole point, segment intersection and endpoint;
  76138. // if there are no points found, we have a valid connection;
  76139. // otherwise choose the point of the minimum angle with the ray as connection point
  76140. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  76141. p = m.next;
  76142. while (p !== stop) {
  76143. if (hx >= p.x &&
  76144. p.x >= mx &&
  76145. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  76146. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  76147. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  76148. m = p;
  76149. tanMin = tan;
  76150. }
  76151. }
  76152. p = p.next;
  76153. }
  76154. return m;
  76155. }
  76156. // interlink polygon nodes in z-order
  76157. function indexCurve(start, minX, minY, size) {
  76158. var p = start;
  76159. do {
  76160. if (p.z === null)
  76161. p.z = zOrder(p.x, p.y, minX, minY, size);
  76162. p.prevZ = p.prev;
  76163. p.nextZ = p.next;
  76164. p = p.next;
  76165. } while (p !== start);
  76166. p.prevZ.nextZ = null;
  76167. p.prevZ = null;
  76168. sortLinked(p);
  76169. }
  76170. // Simon Tatham's linked list merge sort algorithm
  76171. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  76172. function sortLinked(list) {
  76173. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  76174. do {
  76175. p = list;
  76176. list = null;
  76177. tail = null;
  76178. numMerges = 0;
  76179. while (p) {
  76180. numMerges++;
  76181. q = p;
  76182. pSize = 0;
  76183. for (i = 0; i < inSize; i++) {
  76184. pSize++;
  76185. q = q.nextZ;
  76186. if (!q)
  76187. break;
  76188. }
  76189. qSize = inSize;
  76190. while (pSize > 0 || (qSize > 0 && q)) {
  76191. if (pSize === 0) {
  76192. e = q;
  76193. q = q.nextZ;
  76194. qSize--;
  76195. }
  76196. else if (qSize === 0 || !q) {
  76197. e = p;
  76198. p = p.nextZ;
  76199. pSize--;
  76200. }
  76201. else if (p.z <= q.z) {
  76202. e = p;
  76203. p = p.nextZ;
  76204. pSize--;
  76205. }
  76206. else {
  76207. e = q;
  76208. q = q.nextZ;
  76209. qSize--;
  76210. }
  76211. if (tail)
  76212. tail.nextZ = e;
  76213. else
  76214. list = e;
  76215. e.prevZ = tail;
  76216. tail = e;
  76217. }
  76218. p = q;
  76219. }
  76220. tail.nextZ = null;
  76221. inSize *= 2;
  76222. } while (numMerges > 1);
  76223. return list;
  76224. }
  76225. // z-order of a point given coords and size of the data bounding box
  76226. function zOrder(x, y, minX, minY, size) {
  76227. // coords are transformed into non-negative 15-bit integer range
  76228. x = 32767 * (x - minX) / size;
  76229. y = 32767 * (y - minY) / size;
  76230. x = (x | (x << 8)) & 0x00FF00FF;
  76231. x = (x | (x << 4)) & 0x0F0F0F0F;
  76232. x = (x | (x << 2)) & 0x33333333;
  76233. x = (x | (x << 1)) & 0x55555555;
  76234. y = (y | (y << 8)) & 0x00FF00FF;
  76235. y = (y | (y << 4)) & 0x0F0F0F0F;
  76236. y = (y | (y << 2)) & 0x33333333;
  76237. y = (y | (y << 1)) & 0x55555555;
  76238. return x | (y << 1);
  76239. }
  76240. // find the leftmost node of a polygon ring
  76241. function getLeftmost(start) {
  76242. var p = start, leftmost = start;
  76243. do {
  76244. if (p.x < leftmost.x)
  76245. leftmost = p;
  76246. p = p.next;
  76247. } while (p !== start);
  76248. return leftmost;
  76249. }
  76250. // check if a point lies within a convex triangle
  76251. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  76252. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  76253. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  76254. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  76255. }
  76256. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  76257. function isValidDiagonal(a, b) {
  76258. return a.next.i !== b.i &&
  76259. a.prev.i !== b.i &&
  76260. !intersectsPolygon(a, b) &&
  76261. locallyInside(a, b) &&
  76262. locallyInside(b, a) &&
  76263. middleInside(a, b);
  76264. }
  76265. // signed area of a triangle
  76266. function area(p, q, r) {
  76267. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  76268. }
  76269. // check if two points are equal
  76270. function equals(p1, p2) {
  76271. return p1.x === p2.x && p1.y === p2.y;
  76272. }
  76273. // check if two segments intersect
  76274. function intersects(p1, q1, p2, q2) {
  76275. if ((equals(p1, q1) && equals(p2, q2)) ||
  76276. (equals(p1, q2) && equals(p2, q1)))
  76277. return true;
  76278. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  76279. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  76280. }
  76281. // check if a polygon diagonal intersects any polygon segments
  76282. function intersectsPolygon(a, b) {
  76283. var p = a;
  76284. do {
  76285. if (p.i !== a.i &&
  76286. p.next.i !== a.i &&
  76287. p.i !== b.i &&
  76288. p.next.i !== b.i &&
  76289. intersects(p, p.next, a, b))
  76290. return true;
  76291. p = p.next;
  76292. } while (p !== a);
  76293. return false;
  76294. }
  76295. // check if a polygon diagonal is locally inside the polygon
  76296. function locallyInside(a, b) {
  76297. return area(a.prev, a, a.next) < 0
  76298. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  76299. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  76300. }
  76301. // check if the middle point of a polygon diagonal is inside the polygon
  76302. function middleInside(a, b) {
  76303. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  76304. do {
  76305. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  76306. inside = !inside;
  76307. p = p.next;
  76308. } while (p !== a);
  76309. return inside;
  76310. }
  76311. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  76312. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  76313. function splitPolygon(a, b) {
  76314. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  76315. a.next = b;
  76316. b.prev = a;
  76317. a2.next = an;
  76318. an.prev = a2;
  76319. b2.next = a2;
  76320. a2.prev = b2;
  76321. bp.next = b2;
  76322. b2.prev = bp;
  76323. return b2;
  76324. }
  76325. // create a node and optionally link it with previous one (in a circular doubly linked list)
  76326. function insertNode(i, x, y, last) {
  76327. var p = new Node(i, x, y);
  76328. if (!last) {
  76329. p.prev = p;
  76330. p.next = p;
  76331. }
  76332. else {
  76333. p.next = last.next;
  76334. p.prev = last;
  76335. last.next.prev = p;
  76336. last.next = p;
  76337. }
  76338. return p;
  76339. }
  76340. function removeNode(p) {
  76341. p.next.prev = p.prev;
  76342. p.prev.next = p.next;
  76343. if (p.prevZ)
  76344. p.prevZ.nextZ = p.nextZ;
  76345. if (p.nextZ)
  76346. p.nextZ.prevZ = p.prevZ;
  76347. }
  76348. /**
  76349. * return a percentage difference between the polygon area and its triangulation area;
  76350. * used to verify correctness of triangulation
  76351. */
  76352. function deviation(data, holeIndices, dim, triangles) {
  76353. var hasHoles = holeIndices && holeIndices.length;
  76354. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  76355. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  76356. if (hasHoles) {
  76357. for (var i = 0, len = holeIndices.length; i < len; i++) {
  76358. var start = holeIndices[i] * dim;
  76359. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76360. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  76361. }
  76362. }
  76363. var trianglesArea = 0;
  76364. for (i = 0; i < triangles.length; i += 3) {
  76365. var a = triangles[i] * dim;
  76366. var b = triangles[i + 1] * dim;
  76367. var c = triangles[i + 2] * dim;
  76368. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  76369. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  76370. }
  76371. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  76372. }
  76373. Earcut.deviation = deviation;
  76374. ;
  76375. function signedArea(data, start, end, dim) {
  76376. var sum = 0;
  76377. for (var i = start, j = end - dim; i < end; i += dim) {
  76378. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  76379. j = i;
  76380. }
  76381. return sum;
  76382. }
  76383. /**
  76384. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  76385. */
  76386. function flatten(data) {
  76387. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  76388. for (var i = 0; i < data.length; i++) {
  76389. for (var j = 0; j < data[i].length; j++) {
  76390. for (var d = 0; d < dim; d++)
  76391. result.vertices.push(data[i][j][d]);
  76392. }
  76393. if (i > 0) {
  76394. holeIndex += data[i - 1].length;
  76395. result.holes.push(holeIndex);
  76396. }
  76397. }
  76398. return result;
  76399. }
  76400. Earcut.flatten = flatten;
  76401. ;
  76402. })(Earcut || (Earcut = {}));
  76403. //# sourceMappingURL=babylon.earcut.js.map
  76404. "use strict";
  76405. var BABYLON;
  76406. (function (BABYLON) {
  76407. var IndexedVector2 = /** @class */ (function (_super) {
  76408. __extends(IndexedVector2, _super);
  76409. function IndexedVector2(original, index) {
  76410. var _this = _super.call(this, original.x, original.y) || this;
  76411. _this.index = index;
  76412. return _this;
  76413. }
  76414. return IndexedVector2;
  76415. }(BABYLON.Vector2));
  76416. var PolygonPoints = /** @class */ (function () {
  76417. function PolygonPoints() {
  76418. this.elements = new Array();
  76419. }
  76420. PolygonPoints.prototype.add = function (originalPoints) {
  76421. var _this = this;
  76422. var result = new Array();
  76423. originalPoints.forEach(function (point) {
  76424. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76425. var newPoint = new IndexedVector2(point, _this.elements.length);
  76426. result.push(newPoint);
  76427. _this.elements.push(newPoint);
  76428. }
  76429. });
  76430. return result;
  76431. };
  76432. PolygonPoints.prototype.computeBounds = function () {
  76433. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76434. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76435. this.elements.forEach(function (point) {
  76436. // x
  76437. if (point.x < lmin.x) {
  76438. lmin.x = point.x;
  76439. }
  76440. else if (point.x > lmax.x) {
  76441. lmax.x = point.x;
  76442. }
  76443. // y
  76444. if (point.y < lmin.y) {
  76445. lmin.y = point.y;
  76446. }
  76447. else if (point.y > lmax.y) {
  76448. lmax.y = point.y;
  76449. }
  76450. });
  76451. return {
  76452. min: lmin,
  76453. max: lmax,
  76454. width: lmax.x - lmin.x,
  76455. height: lmax.y - lmin.y
  76456. };
  76457. };
  76458. return PolygonPoints;
  76459. }());
  76460. var Polygon = /** @class */ (function () {
  76461. function Polygon() {
  76462. }
  76463. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76464. return [
  76465. new BABYLON.Vector2(xmin, ymin),
  76466. new BABYLON.Vector2(xmax, ymin),
  76467. new BABYLON.Vector2(xmax, ymax),
  76468. new BABYLON.Vector2(xmin, ymax)
  76469. ];
  76470. };
  76471. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76472. if (cx === void 0) { cx = 0; }
  76473. if (cy === void 0) { cy = 0; }
  76474. if (numberOfSides === void 0) { numberOfSides = 32; }
  76475. var result = new Array();
  76476. var angle = 0;
  76477. var increment = (Math.PI * 2) / numberOfSides;
  76478. for (var i = 0; i < numberOfSides; i++) {
  76479. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76480. angle -= increment;
  76481. }
  76482. return result;
  76483. };
  76484. Polygon.Parse = function (input) {
  76485. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76486. var i, result = [];
  76487. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76488. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76489. }
  76490. return result;
  76491. };
  76492. Polygon.StartingAt = function (x, y) {
  76493. return BABYLON.Path2.StartingAt(x, y);
  76494. };
  76495. return Polygon;
  76496. }());
  76497. BABYLON.Polygon = Polygon;
  76498. var PolygonMeshBuilder = /** @class */ (function () {
  76499. function PolygonMeshBuilder(name, contours, scene) {
  76500. this._points = new PolygonPoints();
  76501. this._outlinepoints = new PolygonPoints();
  76502. this._holes = new Array();
  76503. this._epoints = new Array();
  76504. this._eholes = new Array();
  76505. this._name = name;
  76506. this._scene = scene;
  76507. var points;
  76508. if (contours instanceof BABYLON.Path2) {
  76509. points = contours.getPoints();
  76510. }
  76511. else {
  76512. points = contours;
  76513. }
  76514. this._addToepoint(points);
  76515. this._points.add(points);
  76516. this._outlinepoints.add(points);
  76517. }
  76518. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76519. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76520. var p = points_1[_i];
  76521. this._epoints.push(p.x, p.y);
  76522. }
  76523. };
  76524. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76525. this._points.add(hole);
  76526. var holepoints = new PolygonPoints();
  76527. holepoints.add(hole);
  76528. this._holes.push(holepoints);
  76529. this._eholes.push(this._epoints.length / 2);
  76530. this._addToepoint(hole);
  76531. return this;
  76532. };
  76533. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76534. var _this = this;
  76535. if (updatable === void 0) { updatable = false; }
  76536. if (depth === void 0) { depth = 0; }
  76537. var result = new BABYLON.Mesh(this._name, this._scene);
  76538. var normals = new Array();
  76539. var positions = new Array();
  76540. var uvs = new Array();
  76541. var bounds = this._points.computeBounds();
  76542. this._points.elements.forEach(function (p) {
  76543. normals.push(0, 1.0, 0);
  76544. positions.push(p.x, 0, p.y);
  76545. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76546. });
  76547. var indices = new Array();
  76548. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76549. for (var i = 0; i < res.length; i++) {
  76550. indices.push(res[i]);
  76551. }
  76552. if (depth > 0) {
  76553. var positionscount = (positions.length / 3); //get the current pointcount
  76554. this._points.elements.forEach(function (p) {
  76555. normals.push(0, -1.0, 0);
  76556. positions.push(p.x, -depth, p.y);
  76557. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76558. });
  76559. var totalCount = indices.length;
  76560. for (var i = 0; i < totalCount; i += 3) {
  76561. var i0 = indices[i + 0];
  76562. var i1 = indices[i + 1];
  76563. var i2 = indices[i + 2];
  76564. indices.push(i2 + positionscount);
  76565. indices.push(i1 + positionscount);
  76566. indices.push(i0 + positionscount);
  76567. }
  76568. //Add the sides
  76569. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76570. this._holes.forEach(function (hole) {
  76571. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76572. });
  76573. }
  76574. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76575. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76576. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76577. result.setIndices(indices);
  76578. return result;
  76579. };
  76580. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76581. var StartIndex = positions.length / 3;
  76582. var ulength = 0;
  76583. for (var i = 0; i < points.elements.length; i++) {
  76584. var p = points.elements[i];
  76585. var p1;
  76586. if ((i + 1) > points.elements.length - 1) {
  76587. p1 = points.elements[0];
  76588. }
  76589. else {
  76590. p1 = points.elements[i + 1];
  76591. }
  76592. positions.push(p.x, 0, p.y);
  76593. positions.push(p.x, -depth, p.y);
  76594. positions.push(p1.x, 0, p1.y);
  76595. positions.push(p1.x, -depth, p1.y);
  76596. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76597. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76598. var v3 = v2.subtract(v1);
  76599. var v4 = new BABYLON.Vector3(0, 1, 0);
  76600. var vn = BABYLON.Vector3.Cross(v3, v4);
  76601. vn = vn.normalize();
  76602. uvs.push(ulength / bounds.width, 0);
  76603. uvs.push(ulength / bounds.width, 1);
  76604. ulength += v3.length();
  76605. uvs.push((ulength / bounds.width), 0);
  76606. uvs.push((ulength / bounds.width), 1);
  76607. if (!flip) {
  76608. normals.push(-vn.x, -vn.y, -vn.z);
  76609. normals.push(-vn.x, -vn.y, -vn.z);
  76610. normals.push(-vn.x, -vn.y, -vn.z);
  76611. normals.push(-vn.x, -vn.y, -vn.z);
  76612. indices.push(StartIndex);
  76613. indices.push(StartIndex + 1);
  76614. indices.push(StartIndex + 2);
  76615. indices.push(StartIndex + 1);
  76616. indices.push(StartIndex + 3);
  76617. indices.push(StartIndex + 2);
  76618. }
  76619. else {
  76620. normals.push(vn.x, vn.y, vn.z);
  76621. normals.push(vn.x, vn.y, vn.z);
  76622. normals.push(vn.x, vn.y, vn.z);
  76623. normals.push(vn.x, vn.y, vn.z);
  76624. indices.push(StartIndex);
  76625. indices.push(StartIndex + 2);
  76626. indices.push(StartIndex + 1);
  76627. indices.push(StartIndex + 1);
  76628. indices.push(StartIndex + 2);
  76629. indices.push(StartIndex + 3);
  76630. }
  76631. StartIndex += 4;
  76632. }
  76633. ;
  76634. };
  76635. return PolygonMeshBuilder;
  76636. }());
  76637. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76638. })(BABYLON || (BABYLON = {}));
  76639. //# sourceMappingURL=babylon.polygonMesh.js.map
  76640. "use strict";
  76641. var BABYLON;
  76642. (function (BABYLON) {
  76643. // Unique ID when we import meshes from Babylon to CSG
  76644. var currentCSGMeshId = 0;
  76645. // # class Vertex
  76646. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76647. // one to provide additional features like texture coordinates and vertex
  76648. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76649. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76650. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76651. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76652. // is not used anywhere else.
  76653. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76654. var Vertex = /** @class */ (function () {
  76655. function Vertex(pos, normal, uv) {
  76656. this.pos = pos;
  76657. this.normal = normal;
  76658. this.uv = uv;
  76659. }
  76660. Vertex.prototype.clone = function () {
  76661. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76662. };
  76663. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76664. // orientation of a polygon is flipped.
  76665. Vertex.prototype.flip = function () {
  76666. this.normal = this.normal.scale(-1);
  76667. };
  76668. // Create a new vertex between this vertex and `other` by linearly
  76669. // interpolating all properties using a parameter of `t`. Subclasses should
  76670. // override this to interpolate additional properties.
  76671. Vertex.prototype.interpolate = function (other, t) {
  76672. 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));
  76673. };
  76674. return Vertex;
  76675. }());
  76676. // # class Plane
  76677. // Represents a plane in 3D space.
  76678. var Plane = /** @class */ (function () {
  76679. function Plane(normal, w) {
  76680. this.normal = normal;
  76681. this.w = w;
  76682. }
  76683. Plane.FromPoints = function (a, b, c) {
  76684. var v0 = c.subtract(a);
  76685. var v1 = b.subtract(a);
  76686. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76687. return null;
  76688. }
  76689. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76690. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76691. };
  76692. Plane.prototype.clone = function () {
  76693. return new Plane(this.normal.clone(), this.w);
  76694. };
  76695. Plane.prototype.flip = function () {
  76696. this.normal.scaleInPlace(-1);
  76697. this.w = -this.w;
  76698. };
  76699. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76700. // fragments in the appropriate lists. Coplanar polygons go into either
  76701. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76702. // respect to this plane. Polygons in front or in back of this plane go into
  76703. // either `front` or `back`.
  76704. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76705. var COPLANAR = 0;
  76706. var FRONT = 1;
  76707. var BACK = 2;
  76708. var SPANNING = 3;
  76709. // Classify each point as well as the entire polygon into one of the above
  76710. // four classes.
  76711. var polygonType = 0;
  76712. var types = [];
  76713. var i;
  76714. var t;
  76715. for (i = 0; i < polygon.vertices.length; i++) {
  76716. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76717. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76718. polygonType |= type;
  76719. types.push(type);
  76720. }
  76721. // Put the polygon in the correct list, splitting it when necessary.
  76722. switch (polygonType) {
  76723. case COPLANAR:
  76724. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76725. break;
  76726. case FRONT:
  76727. front.push(polygon);
  76728. break;
  76729. case BACK:
  76730. back.push(polygon);
  76731. break;
  76732. case SPANNING:
  76733. var f = [], b = [];
  76734. for (i = 0; i < polygon.vertices.length; i++) {
  76735. var j = (i + 1) % polygon.vertices.length;
  76736. var ti = types[i], tj = types[j];
  76737. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76738. if (ti !== BACK)
  76739. f.push(vi);
  76740. if (ti !== FRONT)
  76741. b.push(ti !== BACK ? vi.clone() : vi);
  76742. if ((ti | tj) === SPANNING) {
  76743. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76744. var v = vi.interpolate(vj, t);
  76745. f.push(v);
  76746. b.push(v.clone());
  76747. }
  76748. }
  76749. var poly;
  76750. if (f.length >= 3) {
  76751. poly = new Polygon(f, polygon.shared);
  76752. if (poly.plane)
  76753. front.push(poly);
  76754. }
  76755. if (b.length >= 3) {
  76756. poly = new Polygon(b, polygon.shared);
  76757. if (poly.plane)
  76758. back.push(poly);
  76759. }
  76760. break;
  76761. }
  76762. };
  76763. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76764. // point is on the plane.
  76765. Plane.EPSILON = 1e-5;
  76766. return Plane;
  76767. }());
  76768. // # class Polygon
  76769. // Represents a convex polygon. The vertices used to initialize a polygon must
  76770. // be coplanar and form a convex loop.
  76771. //
  76772. // Each convex polygon has a `shared` property, which is shared between all
  76773. // polygons that are clones of each other or were split from the same polygon.
  76774. // This can be used to define per-polygon properties (such as surface color).
  76775. var Polygon = /** @class */ (function () {
  76776. function Polygon(vertices, shared) {
  76777. this.vertices = vertices;
  76778. this.shared = shared;
  76779. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76780. }
  76781. Polygon.prototype.clone = function () {
  76782. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76783. return new Polygon(vertices, this.shared);
  76784. };
  76785. Polygon.prototype.flip = function () {
  76786. this.vertices.reverse().map(function (v) { v.flip(); });
  76787. this.plane.flip();
  76788. };
  76789. return Polygon;
  76790. }());
  76791. // # class Node
  76792. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76793. // by picking a polygon to split along. That polygon (and all other coplanar
  76794. // polygons) are added directly to that node and the other polygons are added to
  76795. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76796. // no distinction between internal and leaf nodes.
  76797. var Node = /** @class */ (function () {
  76798. function Node(polygons) {
  76799. this.plane = null;
  76800. this.front = null;
  76801. this.back = null;
  76802. this.polygons = new Array();
  76803. if (polygons) {
  76804. this.build(polygons);
  76805. }
  76806. }
  76807. Node.prototype.clone = function () {
  76808. var node = new Node();
  76809. node.plane = this.plane && this.plane.clone();
  76810. node.front = this.front && this.front.clone();
  76811. node.back = this.back && this.back.clone();
  76812. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76813. return node;
  76814. };
  76815. // Convert solid space to empty space and empty space to solid space.
  76816. Node.prototype.invert = function () {
  76817. for (var i = 0; i < this.polygons.length; i++) {
  76818. this.polygons[i].flip();
  76819. }
  76820. if (this.plane) {
  76821. this.plane.flip();
  76822. }
  76823. if (this.front) {
  76824. this.front.invert();
  76825. }
  76826. if (this.back) {
  76827. this.back.invert();
  76828. }
  76829. var temp = this.front;
  76830. this.front = this.back;
  76831. this.back = temp;
  76832. };
  76833. // Recursively remove all polygons in `polygons` that are inside this BSP
  76834. // tree.
  76835. Node.prototype.clipPolygons = function (polygons) {
  76836. if (!this.plane)
  76837. return polygons.slice();
  76838. var front = new Array(), back = new Array();
  76839. for (var i = 0; i < polygons.length; i++) {
  76840. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76841. }
  76842. if (this.front) {
  76843. front = this.front.clipPolygons(front);
  76844. }
  76845. if (this.back) {
  76846. back = this.back.clipPolygons(back);
  76847. }
  76848. else {
  76849. back = [];
  76850. }
  76851. return front.concat(back);
  76852. };
  76853. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76854. // `bsp`.
  76855. Node.prototype.clipTo = function (bsp) {
  76856. this.polygons = bsp.clipPolygons(this.polygons);
  76857. if (this.front)
  76858. this.front.clipTo(bsp);
  76859. if (this.back)
  76860. this.back.clipTo(bsp);
  76861. };
  76862. // Return a list of all polygons in this BSP tree.
  76863. Node.prototype.allPolygons = function () {
  76864. var polygons = this.polygons.slice();
  76865. if (this.front)
  76866. polygons = polygons.concat(this.front.allPolygons());
  76867. if (this.back)
  76868. polygons = polygons.concat(this.back.allPolygons());
  76869. return polygons;
  76870. };
  76871. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76872. // new polygons are filtered down to the bottom of the tree and become new
  76873. // nodes there. Each set of polygons is partitioned using the first polygon
  76874. // (no heuristic is used to pick a good split).
  76875. Node.prototype.build = function (polygons) {
  76876. if (!polygons.length)
  76877. return;
  76878. if (!this.plane)
  76879. this.plane = polygons[0].plane.clone();
  76880. var front = new Array(), back = new Array();
  76881. for (var i = 0; i < polygons.length; i++) {
  76882. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76883. }
  76884. if (front.length) {
  76885. if (!this.front)
  76886. this.front = new Node();
  76887. this.front.build(front);
  76888. }
  76889. if (back.length) {
  76890. if (!this.back)
  76891. this.back = new Node();
  76892. this.back.build(back);
  76893. }
  76894. };
  76895. return Node;
  76896. }());
  76897. var CSG = /** @class */ (function () {
  76898. function CSG() {
  76899. this.polygons = new Array();
  76900. }
  76901. // Convert BABYLON.Mesh to BABYLON.CSG
  76902. CSG.FromMesh = function (mesh) {
  76903. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76904. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76905. if (mesh instanceof BABYLON.Mesh) {
  76906. mesh.computeWorldMatrix(true);
  76907. matrix = mesh.getWorldMatrix();
  76908. meshPosition = mesh.position.clone();
  76909. meshRotation = mesh.rotation.clone();
  76910. if (mesh.rotationQuaternion) {
  76911. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76912. }
  76913. meshScaling = mesh.scaling.clone();
  76914. }
  76915. else {
  76916. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76917. }
  76918. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76919. var subMeshes = mesh.subMeshes;
  76920. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76921. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76922. vertices = [];
  76923. for (var j = 0; j < 3; j++) {
  76924. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76925. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76926. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76927. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76928. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76929. vertex = new Vertex(position, normal, uv);
  76930. vertices.push(vertex);
  76931. }
  76932. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76933. // To handle the case of degenerated triangle
  76934. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76935. if (polygon.plane)
  76936. polygons.push(polygon);
  76937. }
  76938. }
  76939. var csg = CSG.FromPolygons(polygons);
  76940. csg.matrix = matrix;
  76941. csg.position = meshPosition;
  76942. csg.rotation = meshRotation;
  76943. csg.scaling = meshScaling;
  76944. csg.rotationQuaternion = meshRotationQuaternion;
  76945. currentCSGMeshId++;
  76946. return csg;
  76947. };
  76948. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76949. CSG.FromPolygons = function (polygons) {
  76950. var csg = new CSG();
  76951. csg.polygons = polygons;
  76952. return csg;
  76953. };
  76954. CSG.prototype.clone = function () {
  76955. var csg = new CSG();
  76956. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76957. csg.copyTransformAttributes(this);
  76958. return csg;
  76959. };
  76960. CSG.prototype.union = function (csg) {
  76961. var a = new Node(this.clone().polygons);
  76962. var b = new Node(csg.clone().polygons);
  76963. a.clipTo(b);
  76964. b.clipTo(a);
  76965. b.invert();
  76966. b.clipTo(a);
  76967. b.invert();
  76968. a.build(b.allPolygons());
  76969. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76970. };
  76971. CSG.prototype.unionInPlace = function (csg) {
  76972. var a = new Node(this.polygons);
  76973. var b = new Node(csg.polygons);
  76974. a.clipTo(b);
  76975. b.clipTo(a);
  76976. b.invert();
  76977. b.clipTo(a);
  76978. b.invert();
  76979. a.build(b.allPolygons());
  76980. this.polygons = a.allPolygons();
  76981. };
  76982. CSG.prototype.subtract = function (csg) {
  76983. var a = new Node(this.clone().polygons);
  76984. var b = new Node(csg.clone().polygons);
  76985. a.invert();
  76986. a.clipTo(b);
  76987. b.clipTo(a);
  76988. b.invert();
  76989. b.clipTo(a);
  76990. b.invert();
  76991. a.build(b.allPolygons());
  76992. a.invert();
  76993. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76994. };
  76995. CSG.prototype.subtractInPlace = function (csg) {
  76996. var a = new Node(this.polygons);
  76997. var b = new Node(csg.polygons);
  76998. a.invert();
  76999. a.clipTo(b);
  77000. b.clipTo(a);
  77001. b.invert();
  77002. b.clipTo(a);
  77003. b.invert();
  77004. a.build(b.allPolygons());
  77005. a.invert();
  77006. this.polygons = a.allPolygons();
  77007. };
  77008. CSG.prototype.intersect = function (csg) {
  77009. var a = new Node(this.clone().polygons);
  77010. var b = new Node(csg.clone().polygons);
  77011. a.invert();
  77012. b.clipTo(a);
  77013. b.invert();
  77014. a.clipTo(b);
  77015. b.clipTo(a);
  77016. a.build(b.allPolygons());
  77017. a.invert();
  77018. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77019. };
  77020. CSG.prototype.intersectInPlace = function (csg) {
  77021. var a = new Node(this.polygons);
  77022. var b = new Node(csg.polygons);
  77023. a.invert();
  77024. b.clipTo(a);
  77025. b.invert();
  77026. a.clipTo(b);
  77027. b.clipTo(a);
  77028. a.build(b.allPolygons());
  77029. a.invert();
  77030. this.polygons = a.allPolygons();
  77031. };
  77032. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  77033. // not modified.
  77034. CSG.prototype.inverse = function () {
  77035. var csg = this.clone();
  77036. csg.inverseInPlace();
  77037. return csg;
  77038. };
  77039. CSG.prototype.inverseInPlace = function () {
  77040. this.polygons.map(function (p) { p.flip(); });
  77041. };
  77042. // This is used to keep meshes transformations so they can be restored
  77043. // when we build back a Babylon Mesh
  77044. // NB : All CSG operations are performed in world coordinates
  77045. CSG.prototype.copyTransformAttributes = function (csg) {
  77046. this.matrix = csg.matrix;
  77047. this.position = csg.position;
  77048. this.rotation = csg.rotation;
  77049. this.scaling = csg.scaling;
  77050. this.rotationQuaternion = csg.rotationQuaternion;
  77051. return this;
  77052. };
  77053. // Build Raw mesh from CSG
  77054. // Coordinates here are in world space
  77055. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  77056. var matrix = this.matrix.clone();
  77057. matrix.invert();
  77058. 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;
  77059. if (keepSubMeshes) {
  77060. // Sort Polygons, since subMeshes are indices range
  77061. polygons.sort(function (a, b) {
  77062. if (a.shared.meshId === b.shared.meshId) {
  77063. return a.shared.subMeshId - b.shared.subMeshId;
  77064. }
  77065. else {
  77066. return a.shared.meshId - b.shared.meshId;
  77067. }
  77068. });
  77069. }
  77070. for (var i = 0, il = polygons.length; i < il; i++) {
  77071. polygon = polygons[i];
  77072. // Building SubMeshes
  77073. if (!subMesh_dict[polygon.shared.meshId]) {
  77074. subMesh_dict[polygon.shared.meshId] = {};
  77075. }
  77076. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  77077. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  77078. indexStart: +Infinity,
  77079. indexEnd: -Infinity,
  77080. materialIndex: polygon.shared.materialIndex
  77081. };
  77082. }
  77083. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  77084. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  77085. polygonIndices[0] = 0;
  77086. polygonIndices[1] = j - 1;
  77087. polygonIndices[2] = j;
  77088. for (var k = 0; k < 3; k++) {
  77089. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  77090. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  77091. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  77092. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  77093. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  77094. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  77095. // Check if 2 points can be merged
  77096. if (!(typeof vertex_idx !== 'undefined' &&
  77097. normals[vertex_idx * 3] === localNormal.x &&
  77098. normals[vertex_idx * 3 + 1] === localNormal.y &&
  77099. normals[vertex_idx * 3 + 2] === localNormal.z &&
  77100. uvs[vertex_idx * 2] === uv.x &&
  77101. uvs[vertex_idx * 2 + 1] === uv.y)) {
  77102. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  77103. uvs.push(uv.x, uv.y);
  77104. normals.push(normal.x, normal.y, normal.z);
  77105. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  77106. }
  77107. indices.push(vertex_idx);
  77108. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  77109. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  77110. currentIndex++;
  77111. }
  77112. }
  77113. }
  77114. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  77115. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  77116. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  77117. mesh.setIndices(indices, null);
  77118. if (keepSubMeshes) {
  77119. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  77120. var materialIndexOffset = 0, materialMaxIndex;
  77121. mesh.subMeshes = new Array();
  77122. for (var m in subMesh_dict) {
  77123. materialMaxIndex = -1;
  77124. for (var sm in subMesh_dict[m]) {
  77125. subMesh_obj = subMesh_dict[m][sm];
  77126. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  77127. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  77128. }
  77129. materialIndexOffset += ++materialMaxIndex;
  77130. }
  77131. }
  77132. return mesh;
  77133. };
  77134. // Build Mesh from CSG taking material and transforms into account
  77135. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  77136. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  77137. mesh.material = material;
  77138. mesh.position.copyFrom(this.position);
  77139. mesh.rotation.copyFrom(this.rotation);
  77140. if (this.rotationQuaternion) {
  77141. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  77142. }
  77143. mesh.scaling.copyFrom(this.scaling);
  77144. mesh.computeWorldMatrix(true);
  77145. return mesh;
  77146. };
  77147. return CSG;
  77148. }());
  77149. BABYLON.CSG = CSG;
  77150. })(BABYLON || (BABYLON = {}));
  77151. //# sourceMappingURL=babylon.csg.js.map
  77152. "use strict";
  77153. var BABYLON;
  77154. (function (BABYLON) {
  77155. var LensFlare = /** @class */ (function () {
  77156. function LensFlare(size, position, color, imgUrl, system) {
  77157. this.size = size;
  77158. this.position = position;
  77159. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77160. this.color = color || new BABYLON.Color3(1, 1, 1);
  77161. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  77162. this._system = system;
  77163. system.lensFlares.push(this);
  77164. }
  77165. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  77166. return new LensFlare(size, position, color, imgUrl, system);
  77167. };
  77168. LensFlare.prototype.dispose = function () {
  77169. if (this.texture) {
  77170. this.texture.dispose();
  77171. }
  77172. // Remove from scene
  77173. var index = this._system.lensFlares.indexOf(this);
  77174. this._system.lensFlares.splice(index, 1);
  77175. };
  77176. ;
  77177. return LensFlare;
  77178. }());
  77179. BABYLON.LensFlare = LensFlare;
  77180. })(BABYLON || (BABYLON = {}));
  77181. //# sourceMappingURL=babylon.lensFlare.js.map
  77182. "use strict";
  77183. var BABYLON;
  77184. (function (BABYLON) {
  77185. var LensFlareSystem = /** @class */ (function () {
  77186. function LensFlareSystem(name, emitter, scene) {
  77187. this.name = name;
  77188. this.lensFlares = new Array();
  77189. this.borderLimit = 300;
  77190. this.viewportBorder = 0;
  77191. this.layerMask = 0x0FFFFFFF;
  77192. this._vertexBuffers = {};
  77193. this._isEnabled = true;
  77194. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77195. this._emitter = emitter;
  77196. this.id = name;
  77197. scene.lensFlareSystems.push(this);
  77198. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  77199. var engine = scene.getEngine();
  77200. // VBO
  77201. var vertices = [];
  77202. vertices.push(1, 1);
  77203. vertices.push(-1, 1);
  77204. vertices.push(-1, -1);
  77205. vertices.push(1, -1);
  77206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77207. // Indices
  77208. var indices = [];
  77209. indices.push(0);
  77210. indices.push(1);
  77211. indices.push(2);
  77212. indices.push(0);
  77213. indices.push(2);
  77214. indices.push(3);
  77215. this._indexBuffer = engine.createIndexBuffer(indices);
  77216. // Effects
  77217. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  77218. }
  77219. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  77220. get: function () {
  77221. return this._isEnabled;
  77222. },
  77223. set: function (value) {
  77224. this._isEnabled = value;
  77225. },
  77226. enumerable: true,
  77227. configurable: true
  77228. });
  77229. LensFlareSystem.prototype.getScene = function () {
  77230. return this._scene;
  77231. };
  77232. LensFlareSystem.prototype.getEmitter = function () {
  77233. return this._emitter;
  77234. };
  77235. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  77236. this._emitter = newEmitter;
  77237. };
  77238. LensFlareSystem.prototype.getEmitterPosition = function () {
  77239. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  77240. };
  77241. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  77242. var position = this.getEmitterPosition();
  77243. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  77244. this._positionX = position.x;
  77245. this._positionY = position.y;
  77246. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  77247. if (this.viewportBorder > 0) {
  77248. globalViewport.x -= this.viewportBorder;
  77249. globalViewport.y -= this.viewportBorder;
  77250. globalViewport.width += this.viewportBorder * 2;
  77251. globalViewport.height += this.viewportBorder * 2;
  77252. position.x += this.viewportBorder;
  77253. position.y += this.viewportBorder;
  77254. this._positionX += this.viewportBorder;
  77255. this._positionY += this.viewportBorder;
  77256. }
  77257. if (position.z > 0) {
  77258. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77259. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77260. return true;
  77261. }
  77262. return true;
  77263. }
  77264. return false;
  77265. };
  77266. LensFlareSystem.prototype._isVisible = function () {
  77267. if (!this._isEnabled || !this._scene.activeCamera) {
  77268. return false;
  77269. }
  77270. var emitterPosition = this.getEmitterPosition();
  77271. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77272. var distance = direction.length();
  77273. direction.normalize();
  77274. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77275. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77276. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77277. };
  77278. LensFlareSystem.prototype.render = function () {
  77279. if (!this._effect.isReady() || !this._scene.activeCamera)
  77280. return false;
  77281. var engine = this._scene.getEngine();
  77282. var viewport = this._scene.activeCamera.viewport;
  77283. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77284. // Position
  77285. if (!this.computeEffectivePosition(globalViewport)) {
  77286. return false;
  77287. }
  77288. // Visibility
  77289. if (!this._isVisible()) {
  77290. return false;
  77291. }
  77292. // Intensity
  77293. var awayX;
  77294. var awayY;
  77295. if (this._positionX < this.borderLimit + globalViewport.x) {
  77296. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77297. }
  77298. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77299. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77300. }
  77301. else {
  77302. awayX = 0;
  77303. }
  77304. if (this._positionY < this.borderLimit + globalViewport.y) {
  77305. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77306. }
  77307. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77308. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77309. }
  77310. else {
  77311. awayY = 0;
  77312. }
  77313. var away = (awayX > awayY) ? awayX : awayY;
  77314. away -= this.viewportBorder;
  77315. if (away > this.borderLimit) {
  77316. away = this.borderLimit;
  77317. }
  77318. var intensity = 1.0 - (away / this.borderLimit);
  77319. if (intensity < 0) {
  77320. return false;
  77321. }
  77322. if (intensity > 1.0) {
  77323. intensity = 1.0;
  77324. }
  77325. if (this.viewportBorder > 0) {
  77326. globalViewport.x += this.viewportBorder;
  77327. globalViewport.y += this.viewportBorder;
  77328. globalViewport.width -= this.viewportBorder * 2;
  77329. globalViewport.height -= this.viewportBorder * 2;
  77330. this._positionX -= this.viewportBorder;
  77331. this._positionY -= this.viewportBorder;
  77332. }
  77333. // Position
  77334. var centerX = globalViewport.x + globalViewport.width / 2;
  77335. var centerY = globalViewport.y + globalViewport.height / 2;
  77336. var distX = centerX - this._positionX;
  77337. var distY = centerY - this._positionY;
  77338. // Effects
  77339. engine.enableEffect(this._effect);
  77340. engine.setState(false);
  77341. engine.setDepthBuffer(false);
  77342. // VBOs
  77343. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77344. // Flares
  77345. for (var index = 0; index < this.lensFlares.length; index++) {
  77346. var flare = this.lensFlares[index];
  77347. engine.setAlphaMode(flare.alphaMode);
  77348. var x = centerX - (distX * flare.position);
  77349. var y = centerY - (distY * flare.position);
  77350. var cw = flare.size;
  77351. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77352. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77353. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77354. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77355. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77356. // Texture
  77357. this._effect.setTexture("textureSampler", flare.texture);
  77358. // Color
  77359. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77360. // Draw order
  77361. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77362. }
  77363. engine.setDepthBuffer(true);
  77364. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77365. return true;
  77366. };
  77367. LensFlareSystem.prototype.dispose = function () {
  77368. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77369. if (vertexBuffer) {
  77370. vertexBuffer.dispose();
  77371. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77372. }
  77373. if (this._indexBuffer) {
  77374. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77375. this._indexBuffer = null;
  77376. }
  77377. while (this.lensFlares.length) {
  77378. this.lensFlares[0].dispose();
  77379. }
  77380. // Remove from scene
  77381. var index = this._scene.lensFlareSystems.indexOf(this);
  77382. this._scene.lensFlareSystems.splice(index, 1);
  77383. };
  77384. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77385. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77386. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77387. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77388. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77389. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77390. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77391. var parsedFlare = parsedLensFlareSystem.flares[index];
  77392. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77393. }
  77394. return lensFlareSystem;
  77395. };
  77396. LensFlareSystem.prototype.serialize = function () {
  77397. var serializationObject = {};
  77398. serializationObject.id = this.id;
  77399. serializationObject.name = this.name;
  77400. serializationObject.emitterId = this.getEmitter().id;
  77401. serializationObject.borderLimit = this.borderLimit;
  77402. serializationObject.flares = [];
  77403. for (var index = 0; index < this.lensFlares.length; index++) {
  77404. var flare = this.lensFlares[index];
  77405. serializationObject.flares.push({
  77406. size: flare.size,
  77407. position: flare.position,
  77408. color: flare.color.asArray(),
  77409. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77410. });
  77411. }
  77412. return serializationObject;
  77413. };
  77414. return LensFlareSystem;
  77415. }());
  77416. BABYLON.LensFlareSystem = LensFlareSystem;
  77417. })(BABYLON || (BABYLON = {}));
  77418. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77419. "use strict";
  77420. var BABYLON;
  77421. (function (BABYLON) {
  77422. /**
  77423. * This is a holder class for the physics joint created by the physics plugin.
  77424. * It holds a set of functions to control the underlying joint.
  77425. */
  77426. var PhysicsJoint = /** @class */ (function () {
  77427. function PhysicsJoint(type, jointData) {
  77428. this.type = type;
  77429. this.jointData = jointData;
  77430. jointData.nativeParams = jointData.nativeParams || {};
  77431. }
  77432. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77433. get: function () {
  77434. return this._physicsJoint;
  77435. },
  77436. set: function (newJoint) {
  77437. if (this._physicsJoint) {
  77438. //remove from the wolrd
  77439. }
  77440. this._physicsJoint = newJoint;
  77441. },
  77442. enumerable: true,
  77443. configurable: true
  77444. });
  77445. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77446. set: function (physicsPlugin) {
  77447. this._physicsPlugin = physicsPlugin;
  77448. },
  77449. enumerable: true,
  77450. configurable: true
  77451. });
  77452. /**
  77453. * Execute a function that is physics-plugin specific.
  77454. * @param {Function} func the function that will be executed.
  77455. * It accepts two parameters: the physics world and the physics joint.
  77456. */
  77457. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77458. func(this._physicsPlugin.world, this._physicsJoint);
  77459. };
  77460. //TODO check if the native joints are the same
  77461. //Joint Types
  77462. PhysicsJoint.DistanceJoint = 0;
  77463. PhysicsJoint.HingeJoint = 1;
  77464. PhysicsJoint.BallAndSocketJoint = 2;
  77465. PhysicsJoint.WheelJoint = 3;
  77466. PhysicsJoint.SliderJoint = 4;
  77467. //OIMO
  77468. PhysicsJoint.PrismaticJoint = 5;
  77469. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77470. PhysicsJoint.UniversalJoint = 6;
  77471. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77472. //Cannon
  77473. //Similar to a Ball-Joint. Different in params
  77474. PhysicsJoint.PointToPointJoint = 8;
  77475. //Cannon only at the moment
  77476. PhysicsJoint.SpringJoint = 9;
  77477. PhysicsJoint.LockJoint = 10;
  77478. return PhysicsJoint;
  77479. }());
  77480. BABYLON.PhysicsJoint = PhysicsJoint;
  77481. /**
  77482. * A class representing a physics distance joint.
  77483. */
  77484. var DistanceJoint = /** @class */ (function (_super) {
  77485. __extends(DistanceJoint, _super);
  77486. function DistanceJoint(jointData) {
  77487. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77488. }
  77489. /**
  77490. * Update the predefined distance.
  77491. */
  77492. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77493. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77494. };
  77495. return DistanceJoint;
  77496. }(PhysicsJoint));
  77497. BABYLON.DistanceJoint = DistanceJoint;
  77498. var MotorEnabledJoint = /** @class */ (function (_super) {
  77499. __extends(MotorEnabledJoint, _super);
  77500. function MotorEnabledJoint(type, jointData) {
  77501. return _super.call(this, type, jointData) || this;
  77502. }
  77503. /**
  77504. * Set the motor values.
  77505. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77506. * @param {number} force the force to apply
  77507. * @param {number} maxForce max force for this motor.
  77508. */
  77509. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77510. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77511. };
  77512. /**
  77513. * Set the motor's limits.
  77514. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77515. */
  77516. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77517. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77518. };
  77519. return MotorEnabledJoint;
  77520. }(PhysicsJoint));
  77521. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77522. /**
  77523. * This class represents a single hinge physics joint
  77524. */
  77525. var HingeJoint = /** @class */ (function (_super) {
  77526. __extends(HingeJoint, _super);
  77527. function HingeJoint(jointData) {
  77528. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77529. }
  77530. /**
  77531. * Set the motor values.
  77532. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77533. * @param {number} force the force to apply
  77534. * @param {number} maxForce max force for this motor.
  77535. */
  77536. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77537. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77538. };
  77539. /**
  77540. * Set the motor's limits.
  77541. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77542. */
  77543. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77544. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77545. };
  77546. return HingeJoint;
  77547. }(MotorEnabledJoint));
  77548. BABYLON.HingeJoint = HingeJoint;
  77549. /**
  77550. * This class represents a dual hinge physics joint (same as wheel joint)
  77551. */
  77552. var Hinge2Joint = /** @class */ (function (_super) {
  77553. __extends(Hinge2Joint, _super);
  77554. function Hinge2Joint(jointData) {
  77555. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77556. }
  77557. /**
  77558. * Set the motor values.
  77559. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77560. * @param {number} force the force to apply
  77561. * @param {number} maxForce max force for this motor.
  77562. * @param {motorIndex} the motor's index, 0 or 1.
  77563. */
  77564. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77565. if (motorIndex === void 0) { motorIndex = 0; }
  77566. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77567. };
  77568. /**
  77569. * Set the motor limits.
  77570. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77571. * @param {number} upperLimit the upper limit
  77572. * @param {number} lowerLimit lower limit
  77573. * @param {motorIndex} the motor's index, 0 or 1.
  77574. */
  77575. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77576. if (motorIndex === void 0) { motorIndex = 0; }
  77577. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77578. };
  77579. return Hinge2Joint;
  77580. }(MotorEnabledJoint));
  77581. BABYLON.Hinge2Joint = Hinge2Joint;
  77582. })(BABYLON || (BABYLON = {}));
  77583. //# sourceMappingURL=babylon.physicsJoint.js.map
  77584. "use strict";
  77585. var BABYLON;
  77586. (function (BABYLON) {
  77587. var PhysicsImpostor = /** @class */ (function () {
  77588. function PhysicsImpostor(object, type, _options, _scene) {
  77589. if (_options === void 0) { _options = { mass: 0 }; }
  77590. var _this = this;
  77591. this.object = object;
  77592. this.type = type;
  77593. this._options = _options;
  77594. this._scene = _scene;
  77595. this._bodyUpdateRequired = false;
  77596. this._onBeforePhysicsStepCallbacks = new Array();
  77597. this._onAfterPhysicsStepCallbacks = new Array();
  77598. this._onPhysicsCollideCallbacks = [];
  77599. this._deltaPosition = BABYLON.Vector3.Zero();
  77600. this._isDisposed = false;
  77601. //temp variables for parent rotation calculations
  77602. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77603. this._tmpQuat = new BABYLON.Quaternion();
  77604. this._tmpQuat2 = new BABYLON.Quaternion();
  77605. /**
  77606. * this function is executed by the physics engine.
  77607. */
  77608. this.beforeStep = function () {
  77609. if (!_this._physicsEngine) {
  77610. return;
  77611. }
  77612. _this.object.translate(_this._deltaPosition, -1);
  77613. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77614. _this.object.computeWorldMatrix(false);
  77615. if (_this.object.parent && _this.object.rotationQuaternion) {
  77616. _this.getParentsRotation();
  77617. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77618. }
  77619. else {
  77620. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77621. }
  77622. if (!_this._options.disableBidirectionalTransformation) {
  77623. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77624. }
  77625. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77626. func(_this);
  77627. });
  77628. };
  77629. /**
  77630. * this function is executed by the physics engine.
  77631. */
  77632. this.afterStep = function () {
  77633. if (!_this._physicsEngine) {
  77634. return;
  77635. }
  77636. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77637. func(_this);
  77638. });
  77639. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77640. // object has now its world rotation. needs to be converted to local.
  77641. if (_this.object.parent && _this.object.rotationQuaternion) {
  77642. _this.getParentsRotation();
  77643. _this._tmpQuat.conjugateInPlace();
  77644. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77645. }
  77646. // take the position set and make it the absolute position of this object.
  77647. _this.object.setAbsolutePosition(_this.object.position);
  77648. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77649. _this.object.translate(_this._deltaPosition, 1);
  77650. };
  77651. /**
  77652. * Legacy collision detection event support
  77653. */
  77654. this.onCollideEvent = null;
  77655. //event and body object due to cannon's event-based architecture.
  77656. this.onCollide = function (e) {
  77657. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77658. return;
  77659. }
  77660. if (!_this._physicsEngine) {
  77661. return;
  77662. }
  77663. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77664. if (otherImpostor) {
  77665. // Legacy collision detection event support
  77666. if (_this.onCollideEvent) {
  77667. _this.onCollideEvent(_this, otherImpostor);
  77668. }
  77669. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77670. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77671. }).forEach(function (obj) {
  77672. obj.callback(_this, otherImpostor);
  77673. });
  77674. }
  77675. };
  77676. //sanity check!
  77677. if (!this.object) {
  77678. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77679. return;
  77680. }
  77681. //legacy support for old syntax.
  77682. if (!this._scene && object.getScene) {
  77683. this._scene = object.getScene();
  77684. }
  77685. if (!this._scene) {
  77686. return;
  77687. }
  77688. this._physicsEngine = this._scene.getPhysicsEngine();
  77689. if (!this._physicsEngine) {
  77690. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77691. }
  77692. else {
  77693. //set the object's quaternion, if not set
  77694. if (!this.object.rotationQuaternion) {
  77695. if (this.object.rotation) {
  77696. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77697. }
  77698. else {
  77699. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77700. }
  77701. }
  77702. //default options params
  77703. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77704. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77705. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77706. this._joints = [];
  77707. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77708. if (!this.object.parent || this._options.ignoreParent) {
  77709. this._init();
  77710. }
  77711. else if (this.object.parent.physicsImpostor) {
  77712. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77713. }
  77714. }
  77715. }
  77716. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77717. get: function () {
  77718. return this._isDisposed;
  77719. },
  77720. enumerable: true,
  77721. configurable: true
  77722. });
  77723. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77724. get: function () {
  77725. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77726. },
  77727. set: function (value) {
  77728. this.setMass(value);
  77729. },
  77730. enumerable: true,
  77731. configurable: true
  77732. });
  77733. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77734. get: function () {
  77735. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77736. },
  77737. set: function (value) {
  77738. if (!this._physicsEngine) {
  77739. return;
  77740. }
  77741. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77742. },
  77743. enumerable: true,
  77744. configurable: true
  77745. });
  77746. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77747. get: function () {
  77748. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77749. },
  77750. set: function (value) {
  77751. if (!this._physicsEngine) {
  77752. return;
  77753. }
  77754. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77755. },
  77756. enumerable: true,
  77757. configurable: true
  77758. });
  77759. /**
  77760. * This function will completly initialize this impostor.
  77761. * It will create a new body - but only if this mesh has no parent.
  77762. * If it has, this impostor will not be used other than to define the impostor
  77763. * of the child mesh.
  77764. */
  77765. PhysicsImpostor.prototype._init = function () {
  77766. if (!this._physicsEngine) {
  77767. return;
  77768. }
  77769. this._physicsEngine.removeImpostor(this);
  77770. this.physicsBody = null;
  77771. this._parent = this._parent || this._getPhysicsParent();
  77772. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77773. this._physicsEngine.addImpostor(this);
  77774. }
  77775. };
  77776. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77777. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77778. var parentMesh = this.object.parent;
  77779. return parentMesh.physicsImpostor;
  77780. }
  77781. return null;
  77782. };
  77783. /**
  77784. * Should a new body be generated.
  77785. */
  77786. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77787. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77788. };
  77789. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77790. this.forceUpdate();
  77791. };
  77792. /**
  77793. * Force a regeneration of this or the parent's impostor's body.
  77794. * Use under cautious - This will remove all joints already implemented.
  77795. */
  77796. PhysicsImpostor.prototype.forceUpdate = function () {
  77797. this._init();
  77798. if (this.parent && !this._options.ignoreParent) {
  77799. this.parent.forceUpdate();
  77800. }
  77801. };
  77802. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77803. /*public get mesh(): AbstractMesh {
  77804. return this._mesh;
  77805. }*/
  77806. /**
  77807. * Gets the body that holds this impostor. Either its own, or its parent.
  77808. */
  77809. get: function () {
  77810. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77811. },
  77812. /**
  77813. * Set the physics body. Used mainly by the physics engine/plugin
  77814. */
  77815. set: function (physicsBody) {
  77816. if (this._physicsBody && this._physicsEngine) {
  77817. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77818. }
  77819. this._physicsBody = physicsBody;
  77820. this.resetUpdateFlags();
  77821. },
  77822. enumerable: true,
  77823. configurable: true
  77824. });
  77825. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77826. get: function () {
  77827. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77828. },
  77829. set: function (value) {
  77830. this._parent = value;
  77831. },
  77832. enumerable: true,
  77833. configurable: true
  77834. });
  77835. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77836. this._bodyUpdateRequired = false;
  77837. };
  77838. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77839. if (this.object.getBoundingInfo) {
  77840. var q = this.object.rotationQuaternion;
  77841. //reset rotation
  77842. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77843. //calculate the world matrix with no rotation
  77844. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77845. var boundingInfo = this.object.getBoundingInfo();
  77846. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77847. //bring back the rotation
  77848. this.object.rotationQuaternion = q;
  77849. //calculate the world matrix with the new rotation
  77850. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77851. return size;
  77852. }
  77853. else {
  77854. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77855. }
  77856. };
  77857. PhysicsImpostor.prototype.getObjectCenter = function () {
  77858. if (this.object.getBoundingInfo) {
  77859. var boundingInfo = this.object.getBoundingInfo();
  77860. return boundingInfo.boundingBox.centerWorld;
  77861. }
  77862. else {
  77863. return this.object.position;
  77864. }
  77865. };
  77866. /**
  77867. * Get a specific parametes from the options parameter.
  77868. */
  77869. PhysicsImpostor.prototype.getParam = function (paramName) {
  77870. return this._options[paramName];
  77871. };
  77872. /**
  77873. * Sets a specific parameter in the options given to the physics plugin
  77874. */
  77875. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77876. this._options[paramName] = value;
  77877. this._bodyUpdateRequired = true;
  77878. };
  77879. /**
  77880. * Specifically change the body's mass option. Won't recreate the physics body object
  77881. */
  77882. PhysicsImpostor.prototype.setMass = function (mass) {
  77883. if (this.getParam("mass") !== mass) {
  77884. this.setParam("mass", mass);
  77885. }
  77886. if (this._physicsEngine) {
  77887. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77888. }
  77889. };
  77890. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77891. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77892. };
  77893. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77894. if (this._physicsEngine) {
  77895. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77896. }
  77897. };
  77898. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77899. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77900. };
  77901. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77902. if (this._physicsEngine) {
  77903. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77904. }
  77905. };
  77906. /**
  77907. * Execute a function with the physics plugin native code.
  77908. * Provide a function the will have two variables - the world object and the physics body object.
  77909. */
  77910. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77911. if (this._physicsEngine) {
  77912. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77913. }
  77914. };
  77915. /**
  77916. * Register a function that will be executed before the physics world is stepping forward.
  77917. */
  77918. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77919. this._onBeforePhysicsStepCallbacks.push(func);
  77920. };
  77921. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77922. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77923. if (index > -1) {
  77924. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77925. }
  77926. else {
  77927. BABYLON.Tools.Warn("Function to remove was not found");
  77928. }
  77929. };
  77930. /**
  77931. * Register a function that will be executed after the physics step
  77932. */
  77933. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77934. this._onAfterPhysicsStepCallbacks.push(func);
  77935. };
  77936. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77937. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77938. if (index > -1) {
  77939. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77940. }
  77941. else {
  77942. BABYLON.Tools.Warn("Function to remove was not found");
  77943. }
  77944. };
  77945. /**
  77946. * register a function that will be executed when this impostor collides against a different body.
  77947. */
  77948. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77949. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77950. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77951. };
  77952. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77953. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77954. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77955. if (index > -1) {
  77956. this._onPhysicsCollideCallbacks.splice(index, 1);
  77957. }
  77958. else {
  77959. BABYLON.Tools.Warn("Function to remove was not found");
  77960. }
  77961. };
  77962. PhysicsImpostor.prototype.getParentsRotation = function () {
  77963. var parent = this.object.parent;
  77964. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77965. while (parent) {
  77966. if (parent.rotationQuaternion) {
  77967. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77968. }
  77969. else {
  77970. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77971. }
  77972. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77973. parent = parent.parent;
  77974. }
  77975. return this._tmpQuat;
  77976. };
  77977. /**
  77978. * Apply a force
  77979. */
  77980. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77981. if (this._physicsEngine) {
  77982. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77983. }
  77984. return this;
  77985. };
  77986. /**
  77987. * Apply an impulse
  77988. */
  77989. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77990. if (this._physicsEngine) {
  77991. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77992. }
  77993. return this;
  77994. };
  77995. /**
  77996. * A help function to create a joint.
  77997. */
  77998. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77999. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  78000. this.addJoint(otherImpostor, joint);
  78001. return this;
  78002. };
  78003. /**
  78004. * Add a joint to this impostor with a different impostor.
  78005. */
  78006. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  78007. this._joints.push({
  78008. otherImpostor: otherImpostor,
  78009. joint: joint
  78010. });
  78011. if (this._physicsEngine) {
  78012. this._physicsEngine.addJoint(this, otherImpostor, joint);
  78013. }
  78014. return this;
  78015. };
  78016. /**
  78017. * Will keep this body still, in a sleep mode.
  78018. */
  78019. PhysicsImpostor.prototype.sleep = function () {
  78020. if (this._physicsEngine) {
  78021. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  78022. }
  78023. return this;
  78024. };
  78025. /**
  78026. * Wake the body up.
  78027. */
  78028. PhysicsImpostor.prototype.wakeUp = function () {
  78029. if (this._physicsEngine) {
  78030. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  78031. }
  78032. return this;
  78033. };
  78034. PhysicsImpostor.prototype.clone = function (newObject) {
  78035. if (!newObject)
  78036. return null;
  78037. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  78038. };
  78039. PhysicsImpostor.prototype.dispose = function () {
  78040. var _this = this;
  78041. //no dispose if no physics engine is available.
  78042. if (!this._physicsEngine) {
  78043. return;
  78044. }
  78045. this._joints.forEach(function (j) {
  78046. if (_this._physicsEngine) {
  78047. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  78048. }
  78049. });
  78050. //dispose the physics body
  78051. this._physicsEngine.removeImpostor(this);
  78052. if (this.parent) {
  78053. this.parent.forceUpdate();
  78054. }
  78055. else {
  78056. /*this._object.getChildMeshes().forEach(function(mesh) {
  78057. if (mesh.physicsImpostor) {
  78058. if (disposeChildren) {
  78059. mesh.physicsImpostor.dispose();
  78060. mesh.physicsImpostor = null;
  78061. }
  78062. }
  78063. })*/
  78064. }
  78065. this._isDisposed = true;
  78066. };
  78067. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  78068. this._deltaPosition.copyFrom(position);
  78069. };
  78070. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  78071. if (!this._deltaRotation) {
  78072. this._deltaRotation = new BABYLON.Quaternion();
  78073. }
  78074. this._deltaRotation.copyFrom(rotation);
  78075. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  78076. };
  78077. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  78078. if (this._physicsEngine) {
  78079. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  78080. }
  78081. return this;
  78082. };
  78083. PhysicsImpostor.prototype.getRadius = function () {
  78084. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  78085. };
  78086. /**
  78087. * Sync a bone with this impostor
  78088. * @param bone The bone to sync to the impostor.
  78089. * @param boneMesh The mesh that the bone is influencing.
  78090. * @param jointPivot The pivot of the joint / bone in local space.
  78091. * @param distToJoint Optional distance from the impostor to the joint.
  78092. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78093. */
  78094. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  78095. var tempVec = PhysicsImpostor._tmpVecs[0];
  78096. var mesh = this.object;
  78097. if (mesh.rotationQuaternion) {
  78098. if (adjustRotation) {
  78099. var tempQuat = PhysicsImpostor._tmpQuat;
  78100. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  78101. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  78102. }
  78103. else {
  78104. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  78105. }
  78106. }
  78107. tempVec.x = 0;
  78108. tempVec.y = 0;
  78109. tempVec.z = 0;
  78110. if (jointPivot) {
  78111. tempVec.x = jointPivot.x;
  78112. tempVec.y = jointPivot.y;
  78113. tempVec.z = jointPivot.z;
  78114. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  78115. if (distToJoint === undefined || distToJoint === null) {
  78116. distToJoint = jointPivot.length();
  78117. }
  78118. tempVec.x *= distToJoint;
  78119. tempVec.y *= distToJoint;
  78120. tempVec.z *= distToJoint;
  78121. }
  78122. if (bone.getParent()) {
  78123. tempVec.addInPlace(mesh.getAbsolutePosition());
  78124. bone.setAbsolutePosition(tempVec, boneMesh);
  78125. }
  78126. else {
  78127. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  78128. boneMesh.position.x -= tempVec.x;
  78129. boneMesh.position.y -= tempVec.y;
  78130. boneMesh.position.z -= tempVec.z;
  78131. }
  78132. };
  78133. /**
  78134. * Sync impostor to a bone
  78135. * @param bone The bone that the impostor will be synced to.
  78136. * @param boneMesh The mesh that the bone is influencing.
  78137. * @param jointPivot The pivot of the joint / bone in local space.
  78138. * @param distToJoint Optional distance from the impostor to the joint.
  78139. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78140. * @param boneAxis Optional vector3 axis the bone is aligned with
  78141. */
  78142. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  78143. var mesh = this.object;
  78144. if (mesh.rotationQuaternion) {
  78145. if (adjustRotation) {
  78146. var tempQuat = PhysicsImpostor._tmpQuat;
  78147. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  78148. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  78149. }
  78150. else {
  78151. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  78152. }
  78153. }
  78154. var pos = PhysicsImpostor._tmpVecs[0];
  78155. var boneDir = PhysicsImpostor._tmpVecs[1];
  78156. if (!boneAxis) {
  78157. boneAxis = PhysicsImpostor._tmpVecs[2];
  78158. boneAxis.x = 0;
  78159. boneAxis.y = 1;
  78160. boneAxis.z = 0;
  78161. }
  78162. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  78163. bone.getAbsolutePositionToRef(boneMesh, pos);
  78164. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  78165. distToJoint = jointPivot.length();
  78166. }
  78167. if (distToJoint !== undefined && distToJoint !== null) {
  78168. pos.x += boneDir.x * distToJoint;
  78169. pos.y += boneDir.y * distToJoint;
  78170. pos.z += boneDir.z * distToJoint;
  78171. }
  78172. mesh.setAbsolutePosition(pos);
  78173. };
  78174. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  78175. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  78176. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78177. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  78178. //Impostor types
  78179. PhysicsImpostor.NoImpostor = 0;
  78180. PhysicsImpostor.SphereImpostor = 1;
  78181. PhysicsImpostor.BoxImpostor = 2;
  78182. PhysicsImpostor.PlaneImpostor = 3;
  78183. PhysicsImpostor.MeshImpostor = 4;
  78184. PhysicsImpostor.CylinderImpostor = 7;
  78185. PhysicsImpostor.ParticleImpostor = 8;
  78186. PhysicsImpostor.HeightmapImpostor = 9;
  78187. return PhysicsImpostor;
  78188. }());
  78189. BABYLON.PhysicsImpostor = PhysicsImpostor;
  78190. })(BABYLON || (BABYLON = {}));
  78191. //# sourceMappingURL=babylon.physicsImpostor.js.map
  78192. "use strict";
  78193. var BABYLON;
  78194. (function (BABYLON) {
  78195. var PhysicsEngine = /** @class */ (function () {
  78196. function PhysicsEngine(gravity, _physicsPlugin) {
  78197. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  78198. this._physicsPlugin = _physicsPlugin;
  78199. //new methods and parameters
  78200. this._impostors = [];
  78201. this._joints = [];
  78202. if (!this._physicsPlugin.isSupported()) {
  78203. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  78204. + "Please make sure it is included.");
  78205. }
  78206. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  78207. this.setGravity(gravity);
  78208. this.setTimeStep();
  78209. }
  78210. PhysicsEngine.prototype.setGravity = function (gravity) {
  78211. this.gravity = gravity;
  78212. this._physicsPlugin.setGravity(this.gravity);
  78213. };
  78214. /**
  78215. * Set the time step of the physics engine.
  78216. * default is 1/60.
  78217. * To slow it down, enter 1/600 for example.
  78218. * To speed it up, 1/30
  78219. * @param {number} newTimeStep the new timestep to apply to this world.
  78220. */
  78221. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  78222. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  78223. this._physicsPlugin.setTimeStep(newTimeStep);
  78224. };
  78225. /**
  78226. * Get the time step of the physics engine.
  78227. */
  78228. PhysicsEngine.prototype.getTimeStep = function () {
  78229. return this._physicsPlugin.getTimeStep();
  78230. };
  78231. PhysicsEngine.prototype.dispose = function () {
  78232. this._impostors.forEach(function (impostor) {
  78233. impostor.dispose();
  78234. });
  78235. this._physicsPlugin.dispose();
  78236. };
  78237. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  78238. return this._physicsPlugin.name;
  78239. };
  78240. /**
  78241. * Adding a new impostor for the impostor tracking.
  78242. * This will be done by the impostor itself.
  78243. * @param {PhysicsImpostor} impostor the impostor to add
  78244. */
  78245. PhysicsEngine.prototype.addImpostor = function (impostor) {
  78246. impostor.uniqueId = this._impostors.push(impostor);
  78247. //if no parent, generate the body
  78248. if (!impostor.parent) {
  78249. this._physicsPlugin.generatePhysicsBody(impostor);
  78250. }
  78251. };
  78252. /**
  78253. * Remove an impostor from the engine.
  78254. * This impostor and its mesh will not longer be updated by the physics engine.
  78255. * @param {PhysicsImpostor} impostor the impostor to remove
  78256. */
  78257. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78258. var index = this._impostors.indexOf(impostor);
  78259. if (index > -1) {
  78260. var removed = this._impostors.splice(index, 1);
  78261. //Is it needed?
  78262. if (removed.length) {
  78263. //this will also remove it from the world.
  78264. removed[0].physicsBody = null;
  78265. }
  78266. }
  78267. };
  78268. /**
  78269. * Add a joint to the physics engine
  78270. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78271. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78272. * @param {PhysicsJoint} the joint that will connect both impostors.
  78273. */
  78274. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78275. var impostorJoint = {
  78276. mainImpostor: mainImpostor,
  78277. connectedImpostor: connectedImpostor,
  78278. joint: joint
  78279. };
  78280. joint.physicsPlugin = this._physicsPlugin;
  78281. this._joints.push(impostorJoint);
  78282. this._physicsPlugin.generateJoint(impostorJoint);
  78283. };
  78284. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78285. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78286. return (impostorJoint.connectedImpostor === connectedImpostor
  78287. && impostorJoint.joint === joint
  78288. && impostorJoint.mainImpostor === mainImpostor);
  78289. });
  78290. if (matchingJoints.length) {
  78291. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78292. //TODO remove it from the list as well
  78293. }
  78294. };
  78295. /**
  78296. * Called by the scene. no need to call it.
  78297. */
  78298. PhysicsEngine.prototype._step = function (delta) {
  78299. var _this = this;
  78300. //check if any mesh has no body / requires an update
  78301. this._impostors.forEach(function (impostor) {
  78302. if (impostor.isBodyInitRequired()) {
  78303. _this._physicsPlugin.generatePhysicsBody(impostor);
  78304. }
  78305. });
  78306. if (delta > 0.1) {
  78307. delta = 0.1;
  78308. }
  78309. else if (delta <= 0) {
  78310. delta = 1.0 / 60.0;
  78311. }
  78312. this._physicsPlugin.executeStep(delta, this._impostors);
  78313. };
  78314. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78315. return this._physicsPlugin;
  78316. };
  78317. PhysicsEngine.prototype.getImpostors = function () {
  78318. return this._impostors;
  78319. };
  78320. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78321. for (var i = 0; i < this._impostors.length; ++i) {
  78322. if (this._impostors[i].object === object) {
  78323. return this._impostors[i];
  78324. }
  78325. }
  78326. return null;
  78327. };
  78328. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78329. for (var i = 0; i < this._impostors.length; ++i) {
  78330. if (this._impostors[i].physicsBody === body) {
  78331. return this._impostors[i];
  78332. }
  78333. }
  78334. return null;
  78335. };
  78336. // Statics
  78337. PhysicsEngine.Epsilon = 0.001;
  78338. return PhysicsEngine;
  78339. }());
  78340. BABYLON.PhysicsEngine = PhysicsEngine;
  78341. })(BABYLON || (BABYLON = {}));
  78342. //# sourceMappingURL=babylon.physicsEngine.js.map
  78343. "use strict";
  78344. var BABYLON;
  78345. (function (BABYLON) {
  78346. var PhysicsHelper = /** @class */ (function () {
  78347. function PhysicsHelper(scene) {
  78348. this._scene = scene;
  78349. this._physicsEngine = this._scene.getPhysicsEngine();
  78350. if (!this._physicsEngine) {
  78351. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78352. }
  78353. }
  78354. /**
  78355. * @param {Vector3} origin the origin of the explosion
  78356. * @param {number} radius the explosion radius
  78357. * @param {number} strength the explosion strength
  78358. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78359. */
  78360. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78361. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78362. if (!this._physicsEngine) {
  78363. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78364. return null;
  78365. }
  78366. var impostors = this._physicsEngine.getImpostors();
  78367. if (impostors.length === 0) {
  78368. return null;
  78369. }
  78370. var event = new PhysicsRadialExplosionEvent(this._scene);
  78371. impostors.forEach(function (impostor) {
  78372. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78373. if (!impostorForceAndContactPoint) {
  78374. return;
  78375. }
  78376. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78377. });
  78378. event.dispose(false);
  78379. return event;
  78380. };
  78381. /**
  78382. * @param {Vector3} origin the origin of the explosion
  78383. * @param {number} radius the explosion radius
  78384. * @param {number} strength the explosion strength
  78385. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78386. */
  78387. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78388. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78389. if (!this._physicsEngine) {
  78390. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78391. return null;
  78392. }
  78393. var impostors = this._physicsEngine.getImpostors();
  78394. if (impostors.length === 0) {
  78395. return null;
  78396. }
  78397. var event = new PhysicsRadialExplosionEvent(this._scene);
  78398. impostors.forEach(function (impostor) {
  78399. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78400. if (!impostorForceAndContactPoint) {
  78401. return;
  78402. }
  78403. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78404. });
  78405. event.dispose(false);
  78406. return event;
  78407. };
  78408. /**
  78409. * @param {Vector3} origin the origin of the explosion
  78410. * @param {number} radius the explosion radius
  78411. * @param {number} strength the explosion strength
  78412. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78413. */
  78414. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78415. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78416. if (!this._physicsEngine) {
  78417. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78418. return null;
  78419. }
  78420. var impostors = this._physicsEngine.getImpostors();
  78421. if (impostors.length === 0) {
  78422. return null;
  78423. }
  78424. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78425. event.dispose(false);
  78426. return event;
  78427. };
  78428. /**
  78429. * @param {Vector3} origin the origin of the updraft
  78430. * @param {number} radius the radius of the updraft
  78431. * @param {number} strength the strength of the updraft
  78432. * @param {number} height the height of the updraft
  78433. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78434. */
  78435. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78436. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78437. if (!this._physicsEngine) {
  78438. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78439. return null;
  78440. }
  78441. if (this._physicsEngine.getImpostors().length === 0) {
  78442. return null;
  78443. }
  78444. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78445. event.dispose(false);
  78446. return event;
  78447. };
  78448. /**
  78449. * @param {Vector3} origin the of the vortex
  78450. * @param {number} radius the radius of the vortex
  78451. * @param {number} strength the strength of the vortex
  78452. * @param {number} height the height of the vortex
  78453. */
  78454. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78455. if (!this._physicsEngine) {
  78456. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78457. return null;
  78458. }
  78459. if (this._physicsEngine.getImpostors().length === 0) {
  78460. return null;
  78461. }
  78462. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78463. event.dispose(false);
  78464. return event;
  78465. };
  78466. return PhysicsHelper;
  78467. }());
  78468. BABYLON.PhysicsHelper = PhysicsHelper;
  78469. /***** Radial explosion *****/
  78470. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78471. function PhysicsRadialExplosionEvent(scene) {
  78472. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78473. this._rays = [];
  78474. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78475. this._scene = scene;
  78476. }
  78477. /**
  78478. * Returns the data related to the radial explosion event (sphere & rays).
  78479. * @returns {PhysicsRadialExplosionEventData}
  78480. */
  78481. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78482. this._dataFetched = true;
  78483. return {
  78484. sphere: this._sphere,
  78485. rays: this._rays,
  78486. };
  78487. };
  78488. /**
  78489. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78490. * @param impostor
  78491. * @param {Vector3} origin the origin of the explosion
  78492. * @param {number} radius the explosion radius
  78493. * @param {number} strength the explosion strength
  78494. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78495. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78496. */
  78497. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78498. if (impostor.mass === 0) {
  78499. return null;
  78500. }
  78501. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78502. return null;
  78503. }
  78504. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78505. return null;
  78506. }
  78507. var impostorObjectCenter = impostor.getObjectCenter();
  78508. var direction = impostorObjectCenter.subtract(origin);
  78509. var ray = new BABYLON.Ray(origin, direction, radius);
  78510. this._rays.push(ray);
  78511. var hit = ray.intersectsMesh(impostor.object);
  78512. var contactPoint = hit.pickedPoint;
  78513. if (!contactPoint) {
  78514. return null;
  78515. }
  78516. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78517. if (distanceFromOrigin > radius) {
  78518. return null;
  78519. }
  78520. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78521. ? strength
  78522. : strength * (1 - (distanceFromOrigin / radius));
  78523. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78524. return { force: force, contactPoint: contactPoint };
  78525. };
  78526. /**
  78527. * Disposes the sphere.
  78528. * @param {bolean} force
  78529. */
  78530. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78531. var _this = this;
  78532. if (force === void 0) { force = true; }
  78533. if (force) {
  78534. this._sphere.dispose();
  78535. }
  78536. else {
  78537. setTimeout(function () {
  78538. if (!_this._dataFetched) {
  78539. _this._sphere.dispose();
  78540. }
  78541. }, 0);
  78542. }
  78543. };
  78544. /*** Helpers ***/
  78545. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78546. if (!this._sphere) {
  78547. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78548. this._sphere.isVisible = false;
  78549. }
  78550. };
  78551. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78552. var impostorObject = impostor.object;
  78553. this._prepareSphere();
  78554. this._sphere.position = origin;
  78555. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78556. this._sphere._updateBoundingInfo();
  78557. this._sphere.computeWorldMatrix(true);
  78558. return this._sphere.intersectsMesh(impostorObject, true);
  78559. };
  78560. return PhysicsRadialExplosionEvent;
  78561. }());
  78562. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78563. /***** Gravitational Field *****/
  78564. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78565. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78566. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78567. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78568. this._physicsHelper = physicsHelper;
  78569. this._scene = scene;
  78570. this._origin = origin;
  78571. this._radius = radius;
  78572. this._strength = strength;
  78573. this._falloff = falloff;
  78574. this._tickCallback = this._tick.bind(this);
  78575. }
  78576. /**
  78577. * Returns the data related to the gravitational field event (sphere).
  78578. * @returns {PhysicsGravitationalFieldEventData}
  78579. */
  78580. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78581. this._dataFetched = true;
  78582. return {
  78583. sphere: this._sphere,
  78584. };
  78585. };
  78586. /**
  78587. * Enables the gravitational field.
  78588. */
  78589. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78590. this._tickCallback.call(this);
  78591. this._scene.registerBeforeRender(this._tickCallback);
  78592. };
  78593. /**
  78594. * Disables the gravitational field.
  78595. */
  78596. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78597. this._scene.unregisterBeforeRender(this._tickCallback);
  78598. };
  78599. /**
  78600. * Disposes the sphere.
  78601. * @param {bolean} force
  78602. */
  78603. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78604. var _this = this;
  78605. if (force === void 0) { force = true; }
  78606. if (force) {
  78607. this._sphere.dispose();
  78608. }
  78609. else {
  78610. setTimeout(function () {
  78611. if (!_this._dataFetched) {
  78612. _this._sphere.dispose();
  78613. }
  78614. }, 0);
  78615. }
  78616. };
  78617. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78618. // Since the params won't change, we fetch the event only once
  78619. if (this._sphere) {
  78620. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78621. }
  78622. else {
  78623. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78624. if (radialExplosionEvent) {
  78625. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78626. }
  78627. }
  78628. };
  78629. return PhysicsGravitationalFieldEvent;
  78630. }());
  78631. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78632. /***** Updraft *****/
  78633. var PhysicsUpdraftEvent = /** @class */ (function () {
  78634. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78635. this._scene = _scene;
  78636. this._origin = _origin;
  78637. this._radius = _radius;
  78638. this._strength = _strength;
  78639. this._height = _height;
  78640. this._updraftMode = _updraftMode;
  78641. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78642. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78643. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78644. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78645. this._physicsEngine = this._scene.getPhysicsEngine();
  78646. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78647. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78648. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78649. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78650. }
  78651. this._tickCallback = this._tick.bind(this);
  78652. }
  78653. /**
  78654. * Returns the data related to the updraft event (cylinder).
  78655. * @returns {PhysicsUpdraftEventData}
  78656. */
  78657. PhysicsUpdraftEvent.prototype.getData = function () {
  78658. this._dataFetched = true;
  78659. return {
  78660. cylinder: this._cylinder,
  78661. };
  78662. };
  78663. /**
  78664. * Enables the updraft.
  78665. */
  78666. PhysicsUpdraftEvent.prototype.enable = function () {
  78667. this._tickCallback.call(this);
  78668. this._scene.registerBeforeRender(this._tickCallback);
  78669. };
  78670. /**
  78671. * Disables the cortex.
  78672. */
  78673. PhysicsUpdraftEvent.prototype.disable = function () {
  78674. this._scene.unregisterBeforeRender(this._tickCallback);
  78675. };
  78676. /**
  78677. * Disposes the sphere.
  78678. * @param {bolean} force
  78679. */
  78680. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78681. var _this = this;
  78682. if (force === void 0) { force = true; }
  78683. if (force) {
  78684. this._cylinder.dispose();
  78685. }
  78686. else {
  78687. setTimeout(function () {
  78688. if (!_this._dataFetched) {
  78689. _this._cylinder.dispose();
  78690. }
  78691. }, 0);
  78692. }
  78693. };
  78694. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78695. if (impostor.mass === 0) {
  78696. return null;
  78697. }
  78698. if (!this._intersectsWithCylinder(impostor)) {
  78699. return null;
  78700. }
  78701. var impostorObjectCenter = impostor.getObjectCenter();
  78702. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78703. var direction = this._originDirection;
  78704. }
  78705. else {
  78706. var direction = impostorObjectCenter.subtract(this._originTop);
  78707. }
  78708. var multiplier = this._strength * -1;
  78709. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78710. return { force: force, contactPoint: impostorObjectCenter };
  78711. };
  78712. PhysicsUpdraftEvent.prototype._tick = function () {
  78713. var _this = this;
  78714. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78715. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78716. if (!impostorForceAndContactPoint) {
  78717. return;
  78718. }
  78719. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78720. });
  78721. };
  78722. /*** Helpers ***/
  78723. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78724. if (!this._cylinder) {
  78725. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78726. height: this._height,
  78727. diameter: this._radius * 2,
  78728. }, this._scene);
  78729. this._cylinder.isVisible = false;
  78730. }
  78731. };
  78732. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78733. var impostorObject = impostor.object;
  78734. this._prepareCylinder();
  78735. this._cylinder.position = this._cylinderPosition;
  78736. return this._cylinder.intersectsMesh(impostorObject, true);
  78737. };
  78738. return PhysicsUpdraftEvent;
  78739. }());
  78740. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78741. /***** Vortex *****/
  78742. var PhysicsVortexEvent = /** @class */ (function () {
  78743. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78744. this._scene = _scene;
  78745. this._origin = _origin;
  78746. this._radius = _radius;
  78747. this._strength = _strength;
  78748. this._height = _height;
  78749. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78750. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78751. this._updraftMultiplier = 0.02;
  78752. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78753. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78754. this._physicsEngine = this._scene.getPhysicsEngine();
  78755. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78756. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78757. this._tickCallback = this._tick.bind(this);
  78758. }
  78759. /**
  78760. * Returns the data related to the vortex event (cylinder).
  78761. * @returns {PhysicsVortexEventData}
  78762. */
  78763. PhysicsVortexEvent.prototype.getData = function () {
  78764. this._dataFetched = true;
  78765. return {
  78766. cylinder: this._cylinder,
  78767. };
  78768. };
  78769. /**
  78770. * Enables the vortex.
  78771. */
  78772. PhysicsVortexEvent.prototype.enable = function () {
  78773. this._tickCallback.call(this);
  78774. this._scene.registerBeforeRender(this._tickCallback);
  78775. };
  78776. /**
  78777. * Disables the cortex.
  78778. */
  78779. PhysicsVortexEvent.prototype.disable = function () {
  78780. this._scene.unregisterBeforeRender(this._tickCallback);
  78781. };
  78782. /**
  78783. * Disposes the sphere.
  78784. * @param {bolean} force
  78785. */
  78786. PhysicsVortexEvent.prototype.dispose = function (force) {
  78787. var _this = this;
  78788. if (force === void 0) { force = true; }
  78789. if (force) {
  78790. this._cylinder.dispose();
  78791. }
  78792. else {
  78793. setTimeout(function () {
  78794. if (!_this._dataFetched) {
  78795. _this._cylinder.dispose();
  78796. }
  78797. }, 0);
  78798. }
  78799. };
  78800. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78801. if (impostor.mass === 0) {
  78802. return null;
  78803. }
  78804. if (!this._intersectsWithCylinder(impostor)) {
  78805. return null;
  78806. }
  78807. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78808. return null;
  78809. }
  78810. var impostorObjectCenter = impostor.getObjectCenter();
  78811. 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)
  78812. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78813. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78814. var hit = ray.intersectsMesh(impostor.object);
  78815. var contactPoint = hit.pickedPoint;
  78816. if (!contactPoint) {
  78817. return null;
  78818. }
  78819. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78820. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78821. var directionToOrigin = contactPoint.normalize();
  78822. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78823. directionToOrigin = directionToOrigin.negate();
  78824. }
  78825. // TODO: find a more physically based solution
  78826. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78827. var forceX = directionToOrigin.x * this._strength / 8;
  78828. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78829. var forceZ = directionToOrigin.z * this._strength / 8;
  78830. }
  78831. else {
  78832. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78833. var forceY = this._originTop.y * this._updraftMultiplier;
  78834. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78835. }
  78836. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78837. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78838. return { force: force, contactPoint: impostorObjectCenter };
  78839. };
  78840. PhysicsVortexEvent.prototype._tick = function () {
  78841. var _this = this;
  78842. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78843. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78844. if (!impostorForceAndContactPoint) {
  78845. return;
  78846. }
  78847. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78848. });
  78849. };
  78850. /*** Helpers ***/
  78851. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78852. if (!this._cylinder) {
  78853. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78854. height: this._height,
  78855. diameter: this._radius * 2,
  78856. }, this._scene);
  78857. this._cylinder.isVisible = false;
  78858. }
  78859. };
  78860. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78861. var impostorObject = impostor.object;
  78862. this._prepareCylinder();
  78863. this._cylinder.position = this._cylinderPosition;
  78864. return this._cylinder.intersectsMesh(impostorObject, true);
  78865. };
  78866. return PhysicsVortexEvent;
  78867. }());
  78868. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78869. /***** Enums *****/
  78870. /**
  78871. * The strenght of the force in correspondence to the distance of the affected object
  78872. */
  78873. var PhysicsRadialImpulseFalloff;
  78874. (function (PhysicsRadialImpulseFalloff) {
  78875. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78876. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78877. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78878. /**
  78879. * The strenght of the force in correspondence to the distance of the affected object
  78880. */
  78881. var PhysicsUpdraftMode;
  78882. (function (PhysicsUpdraftMode) {
  78883. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78884. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78885. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78886. })(BABYLON || (BABYLON = {}));
  78887. //# sourceMappingURL=babylon.physicsHelper.js.map
  78888. "use strict";
  78889. var BABYLON;
  78890. (function (BABYLON) {
  78891. var CannonJSPlugin = /** @class */ (function () {
  78892. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78893. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78894. if (iterations === void 0) { iterations = 10; }
  78895. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78896. this.name = "CannonJSPlugin";
  78897. this._physicsMaterials = new Array();
  78898. this._fixedTimeStep = 1 / 60;
  78899. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78900. this.BJSCANNON = CANNON;
  78901. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78902. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78903. this._tmpPosition = BABYLON.Vector3.Zero();
  78904. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78905. this._tmpUnityRotation = new BABYLON.Quaternion();
  78906. if (!this.isSupported()) {
  78907. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78908. return;
  78909. }
  78910. this._extendNamespace();
  78911. this.world = new this.BJSCANNON.World();
  78912. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78913. this.world.solver.iterations = iterations;
  78914. }
  78915. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78916. this.world.gravity.copy(gravity);
  78917. };
  78918. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78919. this._fixedTimeStep = timeStep;
  78920. };
  78921. CannonJSPlugin.prototype.getTimeStep = function () {
  78922. return this._fixedTimeStep;
  78923. };
  78924. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78925. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78926. };
  78927. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78928. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78929. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78930. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78931. };
  78932. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78933. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78934. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78935. impostor.physicsBody.applyForce(impulse, worldPoint);
  78936. };
  78937. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78938. //parent-child relationship. Does this impostor has a parent impostor?
  78939. if (impostor.parent) {
  78940. if (impostor.physicsBody) {
  78941. this.removePhysicsBody(impostor);
  78942. //TODO is that needed?
  78943. impostor.forceUpdate();
  78944. }
  78945. return;
  78946. }
  78947. //should a new body be created for this impostor?
  78948. if (impostor.isBodyInitRequired()) {
  78949. var shape = this._createShape(impostor);
  78950. //unregister events, if body is being changed
  78951. var oldBody = impostor.physicsBody;
  78952. if (oldBody) {
  78953. this.removePhysicsBody(impostor);
  78954. }
  78955. //create the body and material
  78956. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78957. var bodyCreationObject = {
  78958. mass: impostor.getParam("mass"),
  78959. material: material
  78960. };
  78961. // A simple extend, in case native options were used.
  78962. var nativeOptions = impostor.getParam("nativeOptions");
  78963. for (var key in nativeOptions) {
  78964. if (nativeOptions.hasOwnProperty(key)) {
  78965. bodyCreationObject[key] = nativeOptions[key];
  78966. }
  78967. }
  78968. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78969. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78970. this.world.addEventListener("preStep", impostor.beforeStep);
  78971. this.world.addEventListener("postStep", impostor.afterStep);
  78972. impostor.physicsBody.addShape(shape);
  78973. this.world.add(impostor.physicsBody);
  78974. //try to keep the body moving in the right direction by taking old properties.
  78975. //Should be tested!
  78976. if (oldBody) {
  78977. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78978. impostor.physicsBody[param].copy(oldBody[param]);
  78979. });
  78980. }
  78981. this._processChildMeshes(impostor);
  78982. }
  78983. //now update the body's transformation
  78984. this._updatePhysicsBodyTransformation(impostor);
  78985. };
  78986. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78987. var _this = this;
  78988. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78989. var currentRotation = mainImpostor.object.rotationQuaternion;
  78990. if (meshChildren.length) {
  78991. var processMesh = function (localPosition, mesh) {
  78992. if (!currentRotation || !mesh.rotationQuaternion) {
  78993. return;
  78994. }
  78995. var childImpostor = mesh.getPhysicsImpostor();
  78996. if (childImpostor) {
  78997. var parent = childImpostor.parent;
  78998. if (parent !== mainImpostor) {
  78999. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  79000. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  79001. if (childImpostor.physicsBody) {
  79002. _this.removePhysicsBody(childImpostor);
  79003. childImpostor.physicsBody = null;
  79004. }
  79005. childImpostor.parent = mainImpostor;
  79006. childImpostor.resetUpdateFlags();
  79007. 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));
  79008. //Add the mass of the children.
  79009. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  79010. }
  79011. }
  79012. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  79013. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  79014. };
  79015. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  79016. }
  79017. };
  79018. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79019. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  79020. this.world.removeEventListener("preStep", impostor.beforeStep);
  79021. this.world.removeEventListener("postStep", impostor.afterStep);
  79022. this.world.remove(impostor.physicsBody);
  79023. };
  79024. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79025. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79026. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79027. if (!mainBody || !connectedBody) {
  79028. return;
  79029. }
  79030. var constraint;
  79031. var jointData = impostorJoint.joint.jointData;
  79032. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  79033. var constraintData = {
  79034. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  79035. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  79036. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  79037. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  79038. maxForce: jointData.nativeParams.maxForce,
  79039. collideConnected: !!jointData.collision
  79040. };
  79041. switch (impostorJoint.joint.type) {
  79042. case BABYLON.PhysicsJoint.HingeJoint:
  79043. case BABYLON.PhysicsJoint.Hinge2Joint:
  79044. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  79045. break;
  79046. case BABYLON.PhysicsJoint.DistanceJoint:
  79047. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  79048. break;
  79049. case BABYLON.PhysicsJoint.SpringJoint:
  79050. var springData = jointData;
  79051. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  79052. restLength: springData.length,
  79053. stiffness: springData.stiffness,
  79054. damping: springData.damping,
  79055. localAnchorA: constraintData.pivotA,
  79056. localAnchorB: constraintData.pivotB
  79057. });
  79058. break;
  79059. case BABYLON.PhysicsJoint.LockJoint:
  79060. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  79061. break;
  79062. case BABYLON.PhysicsJoint.PointToPointJoint:
  79063. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79064. default:
  79065. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  79066. break;
  79067. }
  79068. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  79069. constraint.collideConnected = !!jointData.collision;
  79070. impostorJoint.joint.physicsJoint = constraint;
  79071. //don't add spring as constraint, as it is not one.
  79072. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  79073. this.world.addConstraint(constraint);
  79074. }
  79075. else {
  79076. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  79077. constraint.applyForce();
  79078. });
  79079. }
  79080. };
  79081. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79082. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  79083. };
  79084. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  79085. var index;
  79086. var mat;
  79087. for (index = 0; index < this._physicsMaterials.length; index++) {
  79088. mat = this._physicsMaterials[index];
  79089. if (mat.friction === friction && mat.restitution === restitution) {
  79090. return mat;
  79091. }
  79092. }
  79093. var currentMat = new this.BJSCANNON.Material(name);
  79094. currentMat.friction = friction;
  79095. currentMat.restitution = restitution;
  79096. this._physicsMaterials.push(currentMat);
  79097. return currentMat;
  79098. };
  79099. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  79100. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  79101. };
  79102. CannonJSPlugin.prototype._createShape = function (impostor) {
  79103. var object = impostor.object;
  79104. var returnValue;
  79105. var extendSize = impostor.getObjectExtendSize();
  79106. switch (impostor.type) {
  79107. case BABYLON.PhysicsImpostor.SphereImpostor:
  79108. var radiusX = extendSize.x;
  79109. var radiusY = extendSize.y;
  79110. var radiusZ = extendSize.z;
  79111. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  79112. break;
  79113. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  79114. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79115. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  79116. break;
  79117. case BABYLON.PhysicsImpostor.BoxImpostor:
  79118. var box = extendSize.scale(0.5);
  79119. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  79120. break;
  79121. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79122. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  79123. returnValue = new this.BJSCANNON.Plane();
  79124. break;
  79125. case BABYLON.PhysicsImpostor.MeshImpostor:
  79126. // should transform the vertex data to world coordinates!!
  79127. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  79128. var rawFaces = object.getIndices ? object.getIndices() : [];
  79129. if (!rawVerts)
  79130. return;
  79131. // get only scale! so the object could transform correctly.
  79132. var oldPosition = object.position.clone();
  79133. var oldRotation = object.rotation && object.rotation.clone();
  79134. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  79135. object.position.copyFromFloats(0, 0, 0);
  79136. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79137. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79138. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79139. var transform = object.computeWorldMatrix(true);
  79140. // convert rawVerts to object space
  79141. var temp = new Array();
  79142. var index;
  79143. for (index = 0; index < rawVerts.length; index += 3) {
  79144. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  79145. }
  79146. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  79147. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  79148. //now set back the transformation!
  79149. object.position.copyFrom(oldPosition);
  79150. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  79151. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  79152. break;
  79153. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  79154. var oldPosition2 = object.position.clone();
  79155. var oldRotation2 = object.rotation && object.rotation.clone();
  79156. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  79157. object.position.copyFromFloats(0, 0, 0);
  79158. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79159. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79160. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79161. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  79162. returnValue = this._createHeightmap(object);
  79163. object.position.copyFrom(oldPosition2);
  79164. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  79165. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  79166. object.computeWorldMatrix(true);
  79167. break;
  79168. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79169. returnValue = new this.BJSCANNON.Particle();
  79170. break;
  79171. }
  79172. return returnValue;
  79173. };
  79174. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  79175. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79176. var transform = object.computeWorldMatrix(true);
  79177. // convert rawVerts to object space
  79178. var temp = new Array();
  79179. var index;
  79180. for (index = 0; index < pos.length; index += 3) {
  79181. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  79182. }
  79183. pos = temp;
  79184. var matrix = new Array();
  79185. //For now pointDepth will not be used and will be automatically calculated.
  79186. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  79187. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  79188. var boundingInfo = object.getBoundingInfo();
  79189. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  79190. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  79191. var elementSize = dim * 2 / arraySize;
  79192. for (var i = 0; i < pos.length; i = i + 3) {
  79193. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  79194. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  79195. var y = -pos[i + 2] + minY;
  79196. if (!matrix[x]) {
  79197. matrix[x] = [];
  79198. }
  79199. if (!matrix[x][z]) {
  79200. matrix[x][z] = y;
  79201. }
  79202. matrix[x][z] = Math.max(y, matrix[x][z]);
  79203. }
  79204. for (var x = 0; x <= arraySize; ++x) {
  79205. if (!matrix[x]) {
  79206. var loc = 1;
  79207. while (!matrix[(x + loc) % arraySize]) {
  79208. loc++;
  79209. }
  79210. matrix[x] = matrix[(x + loc) % arraySize].slice();
  79211. //console.log("missing x", x);
  79212. }
  79213. for (var z = 0; z <= arraySize; ++z) {
  79214. if (!matrix[x][z]) {
  79215. var loc = 1;
  79216. var newValue;
  79217. while (newValue === undefined) {
  79218. newValue = matrix[x][(z + loc++) % arraySize];
  79219. }
  79220. matrix[x][z] = newValue;
  79221. }
  79222. }
  79223. }
  79224. var shape = new this.BJSCANNON.Heightfield(matrix, {
  79225. elementSize: elementSize
  79226. });
  79227. //For future reference, needed for body transformation
  79228. shape.minY = minY;
  79229. return shape;
  79230. };
  79231. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  79232. var object = impostor.object;
  79233. //make sure it is updated...
  79234. object.computeWorldMatrix && object.computeWorldMatrix(true);
  79235. // The delta between the mesh position and the mesh bounding box center
  79236. var bInfo = object.getBoundingInfo();
  79237. if (!bInfo)
  79238. return;
  79239. var center = impostor.getObjectCenter();
  79240. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  79241. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  79242. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  79243. this._tmpPosition.copyFrom(center);
  79244. var quaternion = object.rotationQuaternion;
  79245. if (!quaternion) {
  79246. return;
  79247. }
  79248. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79249. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79250. //-90 DEG in X, precalculated
  79251. quaternion = quaternion.multiply(this._minus90X);
  79252. //Invert! (Precalculated, 90 deg in X)
  79253. //No need to clone. this will never change.
  79254. impostor.setDeltaRotation(this._plus90X);
  79255. }
  79256. //If it is a heightfield, if should be centered.
  79257. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79258. var mesh = object;
  79259. var boundingInfo = mesh.getBoundingInfo();
  79260. //calculate the correct body position:
  79261. var rotationQuaternion = mesh.rotationQuaternion;
  79262. mesh.rotationQuaternion = this._tmpUnityRotation;
  79263. mesh.computeWorldMatrix(true);
  79264. //get original center with no rotation
  79265. var c = center.clone();
  79266. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79267. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79268. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79269. mesh.setPreTransformMatrix(p);
  79270. mesh.computeWorldMatrix(true);
  79271. //calculate the translation
  79272. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79273. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79274. //add it inverted to the delta
  79275. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79276. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79277. //rotation is back
  79278. mesh.rotationQuaternion = rotationQuaternion;
  79279. mesh.setPreTransformMatrix(oldPivot);
  79280. mesh.computeWorldMatrix(true);
  79281. }
  79282. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79283. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79284. //this._tmpPosition.copyFrom(object.position);
  79285. }
  79286. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79287. //Now update the impostor object
  79288. impostor.physicsBody.position.copy(this._tmpPosition);
  79289. impostor.physicsBody.quaternion.copy(quaternion);
  79290. };
  79291. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79292. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79293. if (impostor.object.rotationQuaternion) {
  79294. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79295. }
  79296. };
  79297. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79298. impostor.physicsBody.position.copy(newPosition);
  79299. impostor.physicsBody.quaternion.copy(newRotation);
  79300. };
  79301. CannonJSPlugin.prototype.isSupported = function () {
  79302. return this.BJSCANNON !== undefined;
  79303. };
  79304. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79305. impostor.physicsBody.velocity.copy(velocity);
  79306. };
  79307. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79308. impostor.physicsBody.angularVelocity.copy(velocity);
  79309. };
  79310. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79311. var v = impostor.physicsBody.velocity;
  79312. if (!v) {
  79313. return null;
  79314. }
  79315. return new BABYLON.Vector3(v.x, v.y, v.z);
  79316. };
  79317. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79318. var v = impostor.physicsBody.angularVelocity;
  79319. if (!v) {
  79320. return null;
  79321. }
  79322. return new BABYLON.Vector3(v.x, v.y, v.z);
  79323. };
  79324. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79325. impostor.physicsBody.mass = mass;
  79326. impostor.physicsBody.updateMassProperties();
  79327. };
  79328. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79329. return impostor.physicsBody.mass;
  79330. };
  79331. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79332. return impostor.physicsBody.material.friction;
  79333. };
  79334. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79335. impostor.physicsBody.material.friction = friction;
  79336. };
  79337. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79338. return impostor.physicsBody.material.restitution;
  79339. };
  79340. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79341. impostor.physicsBody.material.restitution = restitution;
  79342. };
  79343. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79344. impostor.physicsBody.sleep();
  79345. };
  79346. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79347. impostor.physicsBody.wakeUp();
  79348. };
  79349. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79350. joint.physicsJoint.distance = maxDistance;
  79351. };
  79352. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79353. // if (!motorIndex) {
  79354. // joint.physicsJoint.enableMotor();
  79355. // }
  79356. // }
  79357. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79358. // if (!motorIndex) {
  79359. // joint.physicsJoint.disableMotor();
  79360. // }
  79361. // }
  79362. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79363. if (!motorIndex) {
  79364. joint.physicsJoint.enableMotor();
  79365. joint.physicsJoint.setMotorSpeed(speed);
  79366. if (maxForce) {
  79367. this.setLimit(joint, maxForce);
  79368. }
  79369. }
  79370. };
  79371. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79372. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79373. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79374. };
  79375. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79376. var body = impostor.physicsBody;
  79377. mesh.position.x = body.position.x;
  79378. mesh.position.y = body.position.y;
  79379. mesh.position.z = body.position.z;
  79380. if (mesh.rotationQuaternion) {
  79381. mesh.rotationQuaternion.x = body.quaternion.x;
  79382. mesh.rotationQuaternion.y = body.quaternion.y;
  79383. mesh.rotationQuaternion.z = body.quaternion.z;
  79384. mesh.rotationQuaternion.w = body.quaternion.w;
  79385. }
  79386. };
  79387. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79388. var shape = impostor.physicsBody.shapes[0];
  79389. return shape.boundingSphereRadius;
  79390. };
  79391. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79392. var shape = impostor.physicsBody.shapes[0];
  79393. result.x = shape.halfExtents.x * 2;
  79394. result.y = shape.halfExtents.y * 2;
  79395. result.z = shape.halfExtents.z * 2;
  79396. };
  79397. CannonJSPlugin.prototype.dispose = function () {
  79398. };
  79399. CannonJSPlugin.prototype._extendNamespace = function () {
  79400. //this will force cannon to execute at least one step when using interpolation
  79401. var step_tmp1 = new this.BJSCANNON.Vec3();
  79402. var Engine = this.BJSCANNON;
  79403. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79404. maxSubSteps = maxSubSteps || 10;
  79405. timeSinceLastCalled = timeSinceLastCalled || 0;
  79406. if (timeSinceLastCalled === 0) {
  79407. this.internalStep(dt);
  79408. this.time += dt;
  79409. }
  79410. else {
  79411. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79412. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79413. var t0 = performance.now();
  79414. for (var i = 0; i !== internalSteps; i++) {
  79415. this.internalStep(dt);
  79416. if (performance.now() - t0 > dt * 1000) {
  79417. break;
  79418. }
  79419. }
  79420. this.time += timeSinceLastCalled;
  79421. var h = this.time % dt;
  79422. var h_div_dt = h / dt;
  79423. var interpvelo = step_tmp1;
  79424. var bodies = this.bodies;
  79425. for (var j = 0; j !== bodies.length; j++) {
  79426. var b = bodies[j];
  79427. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79428. b.position.vsub(b.previousPosition, interpvelo);
  79429. interpvelo.scale(h_div_dt, interpvelo);
  79430. b.position.vadd(interpvelo, b.interpolatedPosition);
  79431. }
  79432. else {
  79433. b.interpolatedPosition.copy(b.position);
  79434. b.interpolatedQuaternion.copy(b.quaternion);
  79435. }
  79436. }
  79437. }
  79438. };
  79439. };
  79440. return CannonJSPlugin;
  79441. }());
  79442. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79443. })(BABYLON || (BABYLON = {}));
  79444. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79445. "use strict";
  79446. var BABYLON;
  79447. (function (BABYLON) {
  79448. var OimoJSPlugin = /** @class */ (function () {
  79449. function OimoJSPlugin(iterations) {
  79450. this.name = "OimoJSPlugin";
  79451. this._tmpImpostorsArray = [];
  79452. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79453. this.BJSOIMO = OIMO;
  79454. this.world = new this.BJSOIMO.World({
  79455. iterations: iterations
  79456. });
  79457. this.world.clear();
  79458. }
  79459. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79460. this.world.gravity.copy(gravity);
  79461. };
  79462. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79463. this.world.timeStep = timeStep;
  79464. };
  79465. OimoJSPlugin.prototype.getTimeStep = function () {
  79466. return this.world.timeStep;
  79467. };
  79468. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79469. var _this = this;
  79470. impostors.forEach(function (impostor) {
  79471. impostor.beforeStep();
  79472. });
  79473. this.world.step();
  79474. impostors.forEach(function (impostor) {
  79475. impostor.afterStep();
  79476. //update the ordered impostors array
  79477. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79478. });
  79479. //check for collisions
  79480. var contact = this.world.contacts;
  79481. while (contact !== null) {
  79482. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79483. contact = contact.next;
  79484. continue;
  79485. }
  79486. //is this body colliding with any other? get the impostor
  79487. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79488. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79489. if (!mainImpostor || !collidingImpostor) {
  79490. contact = contact.next;
  79491. continue;
  79492. }
  79493. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79494. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79495. contact = contact.next;
  79496. }
  79497. };
  79498. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79499. var mass = impostor.physicsBody.mass;
  79500. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79501. };
  79502. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79503. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79504. this.applyImpulse(impostor, force, contactPoint);
  79505. };
  79506. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79507. var _this = this;
  79508. //parent-child relationship. Does this impostor has a parent impostor?
  79509. if (impostor.parent) {
  79510. if (impostor.physicsBody) {
  79511. this.removePhysicsBody(impostor);
  79512. //TODO is that needed?
  79513. impostor.forceUpdate();
  79514. }
  79515. return;
  79516. }
  79517. if (impostor.isBodyInitRequired()) {
  79518. var bodyConfig = {
  79519. name: impostor.uniqueId,
  79520. //Oimo must have mass, also for static objects.
  79521. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79522. size: [],
  79523. type: [],
  79524. pos: [],
  79525. posShape: [],
  79526. rot: [],
  79527. rotShape: [],
  79528. move: impostor.getParam("mass") !== 0,
  79529. density: impostor.getParam("mass"),
  79530. friction: impostor.getParam("friction"),
  79531. restitution: impostor.getParam("restitution"),
  79532. //Supporting older versions of Oimo
  79533. world: this.world
  79534. };
  79535. var impostors = [impostor];
  79536. var addToArray = function (parent) {
  79537. if (!parent.getChildMeshes)
  79538. return;
  79539. parent.getChildMeshes().forEach(function (m) {
  79540. if (m.physicsImpostor) {
  79541. impostors.push(m.physicsImpostor);
  79542. //m.physicsImpostor._init();
  79543. }
  79544. });
  79545. };
  79546. addToArray(impostor.object);
  79547. var checkWithEpsilon_1 = function (value) {
  79548. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79549. };
  79550. impostors.forEach(function (i) {
  79551. if (!i.object.rotationQuaternion) {
  79552. return;
  79553. }
  79554. //get the correct bounding box
  79555. var oldQuaternion = i.object.rotationQuaternion;
  79556. var rot = oldQuaternion.toEulerAngles();
  79557. var extendSize = i.getObjectExtendSize();
  79558. var radToDeg = 57.295779513082320876;
  79559. if (i === impostor) {
  79560. var center = impostor.getObjectCenter();
  79561. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79562. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79563. //Can also use Array.prototype.push.apply
  79564. bodyConfig.pos.push(center.x);
  79565. bodyConfig.pos.push(center.y);
  79566. bodyConfig.pos.push(center.z);
  79567. bodyConfig.posShape.push(0, 0, 0);
  79568. //tmp solution
  79569. bodyConfig.rot.push(rot.x * radToDeg);
  79570. bodyConfig.rot.push(rot.y * radToDeg);
  79571. bodyConfig.rot.push(rot.z * radToDeg);
  79572. bodyConfig.rotShape.push(0, 0, 0);
  79573. }
  79574. else {
  79575. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79576. bodyConfig.posShape.push(localPosition.x);
  79577. bodyConfig.posShape.push(localPosition.y);
  79578. bodyConfig.posShape.push(localPosition.z);
  79579. bodyConfig.pos.push(0, 0, 0);
  79580. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79581. bodyConfig.rot.push(0);
  79582. bodyConfig.rot.push(0);
  79583. bodyConfig.rot.push(0);
  79584. bodyConfig.rotShape.push(rot.x * radToDeg);
  79585. bodyConfig.rotShape.push(rot.y * radToDeg);
  79586. bodyConfig.rotShape.push(rot.z * radToDeg);
  79587. }
  79588. // register mesh
  79589. switch (i.type) {
  79590. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79591. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79592. case BABYLON.PhysicsImpostor.SphereImpostor:
  79593. var radiusX = extendSize.x;
  79594. var radiusY = extendSize.y;
  79595. var radiusZ = extendSize.z;
  79596. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79597. bodyConfig.type.push('sphere');
  79598. //due to the way oimo works with compounds, add 3 times
  79599. bodyConfig.size.push(size);
  79600. bodyConfig.size.push(size);
  79601. bodyConfig.size.push(size);
  79602. break;
  79603. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79604. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79605. var sizeY = checkWithEpsilon_1(extendSize.y);
  79606. bodyConfig.type.push('cylinder');
  79607. bodyConfig.size.push(sizeX);
  79608. bodyConfig.size.push(sizeY);
  79609. //due to the way oimo works with compounds, add one more value.
  79610. bodyConfig.size.push(sizeY);
  79611. break;
  79612. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79613. case BABYLON.PhysicsImpostor.BoxImpostor:
  79614. default:
  79615. var sizeX = checkWithEpsilon_1(extendSize.x);
  79616. var sizeY = checkWithEpsilon_1(extendSize.y);
  79617. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79618. bodyConfig.type.push('box');
  79619. //if (i === impostor) {
  79620. bodyConfig.size.push(sizeX);
  79621. bodyConfig.size.push(sizeY);
  79622. bodyConfig.size.push(sizeZ);
  79623. //} else {
  79624. // bodyConfig.size.push(0,0,0);
  79625. //}
  79626. break;
  79627. }
  79628. //actually not needed, but hey...
  79629. i.object.rotationQuaternion = oldQuaternion;
  79630. });
  79631. impostor.physicsBody = this.world.add(bodyConfig);
  79632. }
  79633. else {
  79634. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79635. }
  79636. impostor.setDeltaPosition(this._tmpPositionVector);
  79637. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79638. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79639. };
  79640. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79641. //impostor.physicsBody.dispose();
  79642. //Same as : (older oimo versions)
  79643. this.world.removeRigidBody(impostor.physicsBody);
  79644. };
  79645. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79646. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79647. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79648. if (!mainBody || !connectedBody) {
  79649. return;
  79650. }
  79651. var jointData = impostorJoint.joint.jointData;
  79652. var options = jointData.nativeParams || {};
  79653. var type;
  79654. var nativeJointData = {
  79655. body1: mainBody,
  79656. body2: connectedBody,
  79657. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79658. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79659. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79660. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79661. min: options.min,
  79662. max: options.max,
  79663. collision: options.collision || jointData.collision,
  79664. spring: options.spring,
  79665. //supporting older version of Oimo
  79666. world: this.world
  79667. };
  79668. switch (impostorJoint.joint.type) {
  79669. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79670. type = "jointBall";
  79671. break;
  79672. case BABYLON.PhysicsJoint.SpringJoint:
  79673. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79674. var springData = jointData;
  79675. nativeJointData.min = springData.length || nativeJointData.min;
  79676. //Max should also be set, just make sure it is at least min
  79677. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79678. case BABYLON.PhysicsJoint.DistanceJoint:
  79679. type = "jointDistance";
  79680. nativeJointData.max = jointData.maxDistance;
  79681. break;
  79682. case BABYLON.PhysicsJoint.PrismaticJoint:
  79683. type = "jointPrisme";
  79684. break;
  79685. case BABYLON.PhysicsJoint.SliderJoint:
  79686. type = "jointSlide";
  79687. break;
  79688. case BABYLON.PhysicsJoint.WheelJoint:
  79689. type = "jointWheel";
  79690. break;
  79691. case BABYLON.PhysicsJoint.HingeJoint:
  79692. default:
  79693. type = "jointHinge";
  79694. break;
  79695. }
  79696. nativeJointData.type = type;
  79697. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79698. };
  79699. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79700. //Bug in Oimo prevents us from disposing a joint in the playground
  79701. //joint.joint.physicsJoint.dispose();
  79702. //So we will bruteforce it!
  79703. try {
  79704. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79705. }
  79706. catch (e) {
  79707. BABYLON.Tools.Warn(e);
  79708. }
  79709. };
  79710. OimoJSPlugin.prototype.isSupported = function () {
  79711. return this.BJSOIMO !== undefined;
  79712. };
  79713. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79714. if (!impostor.physicsBody.sleeping) {
  79715. //TODO check that
  79716. /*if (impostor.physicsBody.shapes.next) {
  79717. var parentShape = this._getLastShape(impostor.physicsBody);
  79718. impostor.object.position.copyFrom(parentShape.position);
  79719. console.log(parentShape.position);
  79720. } else {*/
  79721. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79722. //}
  79723. if (impostor.object.rotationQuaternion) {
  79724. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79725. }
  79726. }
  79727. };
  79728. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79729. var body = impostor.physicsBody;
  79730. body.position.copy(newPosition);
  79731. body.orientation.copy(newRotation);
  79732. body.syncShapes();
  79733. body.awake();
  79734. };
  79735. /*private _getLastShape(body: any): any {
  79736. var lastShape = body.shapes;
  79737. while (lastShape.next) {
  79738. lastShape = lastShape.next;
  79739. }
  79740. return lastShape;
  79741. }*/
  79742. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79743. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79744. };
  79745. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79746. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79747. };
  79748. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79749. var v = impostor.physicsBody.linearVelocity;
  79750. if (!v) {
  79751. return null;
  79752. }
  79753. return new BABYLON.Vector3(v.x, v.y, v.z);
  79754. };
  79755. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79756. var v = impostor.physicsBody.angularVelocity;
  79757. if (!v) {
  79758. return null;
  79759. }
  79760. return new BABYLON.Vector3(v.x, v.y, v.z);
  79761. };
  79762. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79763. var staticBody = mass === 0;
  79764. //this will actually set the body's density and not its mass.
  79765. //But this is how oimo treats the mass variable.
  79766. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79767. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79768. };
  79769. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79770. return impostor.physicsBody.shapes.density;
  79771. };
  79772. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79773. return impostor.physicsBody.shapes.friction;
  79774. };
  79775. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79776. impostor.physicsBody.shapes.friction = friction;
  79777. };
  79778. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79779. return impostor.physicsBody.shapes.restitution;
  79780. };
  79781. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79782. impostor.physicsBody.shapes.restitution = restitution;
  79783. };
  79784. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79785. impostor.physicsBody.sleep();
  79786. };
  79787. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79788. impostor.physicsBody.awake();
  79789. };
  79790. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79791. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79792. if (minDistance !== void 0) {
  79793. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79794. }
  79795. };
  79796. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79797. //TODO separate rotational and transational motors.
  79798. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79799. if (motor) {
  79800. motor.setMotor(speed, maxForce);
  79801. }
  79802. };
  79803. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79804. //TODO separate rotational and transational motors.
  79805. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79806. if (motor) {
  79807. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79808. }
  79809. };
  79810. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79811. var body = impostor.physicsBody;
  79812. mesh.position.x = body.position.x;
  79813. mesh.position.y = body.position.y;
  79814. mesh.position.z = body.position.z;
  79815. if (mesh.rotationQuaternion) {
  79816. mesh.rotationQuaternion.x = body.orientation.x;
  79817. mesh.rotationQuaternion.y = body.orientation.y;
  79818. mesh.rotationQuaternion.z = body.orientation.z;
  79819. mesh.rotationQuaternion.w = body.orientation.s;
  79820. }
  79821. };
  79822. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79823. return impostor.physicsBody.shapes.radius;
  79824. };
  79825. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79826. var shape = impostor.physicsBody.shapes;
  79827. result.x = shape.halfWidth * 2;
  79828. result.y = shape.halfHeight * 2;
  79829. result.z = shape.halfDepth * 2;
  79830. };
  79831. OimoJSPlugin.prototype.dispose = function () {
  79832. this.world.clear();
  79833. };
  79834. return OimoJSPlugin;
  79835. }());
  79836. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79837. })(BABYLON || (BABYLON = {}));
  79838. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79839. "use strict";
  79840. var BABYLON;
  79841. (function (BABYLON) {
  79842. /*
  79843. * Based on jsTGALoader - Javascript loader for TGA file
  79844. * By Vincent Thibault
  79845. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79846. */
  79847. var TGATools = /** @class */ (function () {
  79848. function TGATools() {
  79849. }
  79850. TGATools.GetTGAHeader = function (data) {
  79851. var offset = 0;
  79852. var header = {
  79853. id_length: data[offset++],
  79854. colormap_type: data[offset++],
  79855. image_type: data[offset++],
  79856. colormap_index: data[offset++] | data[offset++] << 8,
  79857. colormap_length: data[offset++] | data[offset++] << 8,
  79858. colormap_size: data[offset++],
  79859. origin: [
  79860. data[offset++] | data[offset++] << 8,
  79861. data[offset++] | data[offset++] << 8
  79862. ],
  79863. width: data[offset++] | data[offset++] << 8,
  79864. height: data[offset++] | data[offset++] << 8,
  79865. pixel_size: data[offset++],
  79866. flags: data[offset++]
  79867. };
  79868. return header;
  79869. };
  79870. TGATools.UploadContent = function (gl, data) {
  79871. // Not enough data to contain header ?
  79872. if (data.length < 19) {
  79873. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79874. return;
  79875. }
  79876. // Read Header
  79877. var offset = 18;
  79878. var header = TGATools.GetTGAHeader(data);
  79879. // Assume it's a valid Targa file.
  79880. if (header.id_length + offset > data.length) {
  79881. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79882. return;
  79883. }
  79884. // Skip not needed data
  79885. offset += header.id_length;
  79886. var use_rle = false;
  79887. var use_pal = false;
  79888. var use_grey = false;
  79889. // Get some informations.
  79890. switch (header.image_type) {
  79891. case TGATools._TYPE_RLE_INDEXED:
  79892. use_rle = true;
  79893. case TGATools._TYPE_INDEXED:
  79894. use_pal = true;
  79895. break;
  79896. case TGATools._TYPE_RLE_RGB:
  79897. use_rle = true;
  79898. case TGATools._TYPE_RGB:
  79899. // use_rgb = true;
  79900. break;
  79901. case TGATools._TYPE_RLE_GREY:
  79902. use_rle = true;
  79903. case TGATools._TYPE_GREY:
  79904. use_grey = true;
  79905. break;
  79906. }
  79907. var pixel_data;
  79908. // var numAlphaBits = header.flags & 0xf;
  79909. var pixel_size = header.pixel_size >> 3;
  79910. var pixel_total = header.width * header.height * pixel_size;
  79911. // Read palettes
  79912. var palettes;
  79913. if (use_pal) {
  79914. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79915. }
  79916. // Read LRE
  79917. if (use_rle) {
  79918. pixel_data = new Uint8Array(pixel_total);
  79919. var c, count, i;
  79920. var localOffset = 0;
  79921. var pixels = new Uint8Array(pixel_size);
  79922. while (offset < pixel_total && localOffset < pixel_total) {
  79923. c = data[offset++];
  79924. count = (c & 0x7f) + 1;
  79925. // RLE pixels
  79926. if (c & 0x80) {
  79927. // Bind pixel tmp array
  79928. for (i = 0; i < pixel_size; ++i) {
  79929. pixels[i] = data[offset++];
  79930. }
  79931. // Copy pixel array
  79932. for (i = 0; i < count; ++i) {
  79933. pixel_data.set(pixels, localOffset + i * pixel_size);
  79934. }
  79935. localOffset += pixel_size * count;
  79936. }
  79937. else {
  79938. count *= pixel_size;
  79939. for (i = 0; i < count; ++i) {
  79940. pixel_data[localOffset + i] = data[offset++];
  79941. }
  79942. localOffset += count;
  79943. }
  79944. }
  79945. }
  79946. else {
  79947. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79948. }
  79949. // Load to texture
  79950. var x_start, y_start, x_step, y_step, y_end, x_end;
  79951. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79952. default:
  79953. case TGATools._ORIGIN_UL:
  79954. x_start = 0;
  79955. x_step = 1;
  79956. x_end = header.width;
  79957. y_start = 0;
  79958. y_step = 1;
  79959. y_end = header.height;
  79960. break;
  79961. case TGATools._ORIGIN_BL:
  79962. x_start = 0;
  79963. x_step = 1;
  79964. x_end = header.width;
  79965. y_start = header.height - 1;
  79966. y_step = -1;
  79967. y_end = -1;
  79968. break;
  79969. case TGATools._ORIGIN_UR:
  79970. x_start = header.width - 1;
  79971. x_step = -1;
  79972. x_end = -1;
  79973. y_start = 0;
  79974. y_step = 1;
  79975. y_end = header.height;
  79976. break;
  79977. case TGATools._ORIGIN_BR:
  79978. x_start = header.width - 1;
  79979. x_step = -1;
  79980. x_end = -1;
  79981. y_start = header.height - 1;
  79982. y_step = -1;
  79983. y_end = -1;
  79984. break;
  79985. }
  79986. // Load the specify method
  79987. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79988. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79989. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79990. };
  79991. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79992. var image = pixel_data, colormap = palettes;
  79993. var width = header.width, height = header.height;
  79994. var color, i = 0, x, y;
  79995. var imageData = new Uint8Array(width * height * 4);
  79996. for (y = y_start; y !== y_end; y += y_step) {
  79997. for (x = x_start; x !== x_end; x += x_step, i++) {
  79998. color = image[i];
  79999. imageData[(x + width * y) * 4 + 3] = 255;
  80000. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  80001. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  80002. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  80003. }
  80004. }
  80005. return imageData;
  80006. };
  80007. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80008. var image = pixel_data;
  80009. var width = header.width, height = header.height;
  80010. var color, i = 0, x, y;
  80011. var imageData = new Uint8Array(width * height * 4);
  80012. for (y = y_start; y !== y_end; y += y_step) {
  80013. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  80014. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  80015. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  80016. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  80017. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  80018. imageData[(x + width * y) * 4 + 0] = r;
  80019. imageData[(x + width * y) * 4 + 1] = g;
  80020. imageData[(x + width * y) * 4 + 2] = b;
  80021. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  80022. }
  80023. }
  80024. return imageData;
  80025. };
  80026. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80027. var image = pixel_data;
  80028. var width = header.width, height = header.height;
  80029. var i = 0, x, y;
  80030. var imageData = new Uint8Array(width * height * 4);
  80031. for (y = y_start; y !== y_end; y += y_step) {
  80032. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  80033. imageData[(x + width * y) * 4 + 3] = 255;
  80034. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80035. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  80036. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  80037. }
  80038. }
  80039. return imageData;
  80040. };
  80041. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80042. var image = pixel_data;
  80043. var width = header.width, height = header.height;
  80044. var i = 0, x, y;
  80045. var imageData = new Uint8Array(width * height * 4);
  80046. for (y = y_start; y !== y_end; y += y_step) {
  80047. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  80048. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80049. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  80050. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  80051. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  80052. }
  80053. }
  80054. return imageData;
  80055. };
  80056. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80057. var image = pixel_data;
  80058. var width = header.width, height = header.height;
  80059. var color, i = 0, x, y;
  80060. var imageData = new Uint8Array(width * height * 4);
  80061. for (y = y_start; y !== y_end; y += y_step) {
  80062. for (x = x_start; x !== x_end; x += x_step, i++) {
  80063. color = image[i];
  80064. imageData[(x + width * y) * 4 + 0] = color;
  80065. imageData[(x + width * y) * 4 + 1] = color;
  80066. imageData[(x + width * y) * 4 + 2] = color;
  80067. imageData[(x + width * y) * 4 + 3] = 255;
  80068. }
  80069. }
  80070. return imageData;
  80071. };
  80072. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80073. var image = pixel_data;
  80074. var width = header.width, height = header.height;
  80075. var i = 0, x, y;
  80076. var imageData = new Uint8Array(width * height * 4);
  80077. for (y = y_start; y !== y_end; y += y_step) {
  80078. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  80079. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  80080. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  80081. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80082. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  80083. }
  80084. }
  80085. return imageData;
  80086. };
  80087. //private static _TYPE_NO_DATA = 0;
  80088. TGATools._TYPE_INDEXED = 1;
  80089. TGATools._TYPE_RGB = 2;
  80090. TGATools._TYPE_GREY = 3;
  80091. TGATools._TYPE_RLE_INDEXED = 9;
  80092. TGATools._TYPE_RLE_RGB = 10;
  80093. TGATools._TYPE_RLE_GREY = 11;
  80094. TGATools._ORIGIN_MASK = 0x30;
  80095. TGATools._ORIGIN_SHIFT = 0x04;
  80096. TGATools._ORIGIN_BL = 0x00;
  80097. TGATools._ORIGIN_BR = 0x01;
  80098. TGATools._ORIGIN_UL = 0x02;
  80099. TGATools._ORIGIN_UR = 0x03;
  80100. return TGATools;
  80101. }());
  80102. BABYLON.TGATools = TGATools;
  80103. })(BABYLON || (BABYLON = {}));
  80104. //# sourceMappingURL=babylon.tga.js.map
  80105. "use strict";
  80106. var BABYLON;
  80107. (function (BABYLON) {
  80108. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  80109. // All values and structures referenced from:
  80110. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  80111. var DDS_MAGIC = 0x20534444;
  80112. var
  80113. //DDSD_CAPS = 0x1,
  80114. //DDSD_HEIGHT = 0x2,
  80115. //DDSD_WIDTH = 0x4,
  80116. //DDSD_PITCH = 0x8,
  80117. //DDSD_PIXELFORMAT = 0x1000,
  80118. DDSD_MIPMAPCOUNT = 0x20000;
  80119. //DDSD_LINEARSIZE = 0x80000,
  80120. //DDSD_DEPTH = 0x800000;
  80121. // var DDSCAPS_COMPLEX = 0x8,
  80122. // DDSCAPS_MIPMAP = 0x400000,
  80123. // DDSCAPS_TEXTURE = 0x1000;
  80124. var DDSCAPS2_CUBEMAP = 0x200;
  80125. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  80126. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  80127. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  80128. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  80129. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  80130. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  80131. // DDSCAPS2_VOLUME = 0x200000;
  80132. var
  80133. //DDPF_ALPHAPIXELS = 0x1,
  80134. //DDPF_ALPHA = 0x2,
  80135. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  80136. //DDPF_YUV = 0x200,
  80137. DDPF_LUMINANCE = 0x20000;
  80138. function FourCCToInt32(value) {
  80139. return value.charCodeAt(0) +
  80140. (value.charCodeAt(1) << 8) +
  80141. (value.charCodeAt(2) << 16) +
  80142. (value.charCodeAt(3) << 24);
  80143. }
  80144. function Int32ToFourCC(value) {
  80145. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  80146. }
  80147. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  80148. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  80149. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  80150. var FOURCC_DX10 = FourCCToInt32("DX10");
  80151. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  80152. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  80153. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  80154. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  80155. var headerLengthInt = 31; // The header length in 32 bit ints
  80156. // Offsets into the header array
  80157. var off_magic = 0;
  80158. var off_size = 1;
  80159. var off_flags = 2;
  80160. var off_height = 3;
  80161. var off_width = 4;
  80162. var off_mipmapCount = 7;
  80163. var off_pfFlags = 20;
  80164. var off_pfFourCC = 21;
  80165. var off_RGBbpp = 22;
  80166. var off_RMask = 23;
  80167. var off_GMask = 24;
  80168. var off_BMask = 25;
  80169. var off_AMask = 26;
  80170. // var off_caps1 = 27;
  80171. var off_caps2 = 28;
  80172. // var off_caps3 = 29;
  80173. // var off_caps4 = 30;
  80174. var off_dxgiFormat = 32;
  80175. ;
  80176. var DDSTools = /** @class */ (function () {
  80177. function DDSTools() {
  80178. }
  80179. DDSTools.GetDDSInfo = function (arrayBuffer) {
  80180. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80181. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  80182. var mipmapCount = 1;
  80183. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  80184. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80185. }
  80186. var fourCC = header[off_pfFourCC];
  80187. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  80188. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80189. switch (fourCC) {
  80190. case FOURCC_D3DFMT_R16G16B16A16F:
  80191. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80192. break;
  80193. case FOURCC_D3DFMT_R32G32B32A32F:
  80194. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80195. break;
  80196. case FOURCC_DX10:
  80197. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  80198. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80199. break;
  80200. }
  80201. }
  80202. return {
  80203. width: header[off_width],
  80204. height: header[off_height],
  80205. mipmapCount: mipmapCount,
  80206. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  80207. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  80208. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  80209. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  80210. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  80211. dxgiFormat: dxgiFormat,
  80212. textureType: textureType
  80213. };
  80214. };
  80215. DDSTools._ToHalfFloat = function (value) {
  80216. if (!DDSTools._FloatView) {
  80217. DDSTools._FloatView = new Float32Array(1);
  80218. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  80219. }
  80220. DDSTools._FloatView[0] = value;
  80221. var x = DDSTools._Int32View[0];
  80222. var bits = (x >> 16) & 0x8000; /* Get the sign */
  80223. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  80224. var e = (x >> 23) & 0xff; /* Using int is faster here */
  80225. /* If zero, or denormal, or exponent underflows too much for a denormal
  80226. * half, return signed zero. */
  80227. if (e < 103) {
  80228. return bits;
  80229. }
  80230. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  80231. if (e > 142) {
  80232. bits |= 0x7c00;
  80233. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  80234. * not Inf, so make sure we set one mantissa bit too. */
  80235. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  80236. return bits;
  80237. }
  80238. /* If exponent underflows but not too much, return a denormal */
  80239. if (e < 113) {
  80240. m |= 0x0800;
  80241. /* Extra rounding may overflow and set mantissa to 0 and exponent
  80242. * to 1, which is OK. */
  80243. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  80244. return bits;
  80245. }
  80246. bits |= ((e - 112) << 10) | (m >> 1);
  80247. bits += m & 1;
  80248. return bits;
  80249. };
  80250. DDSTools._FromHalfFloat = function (value) {
  80251. var s = (value & 0x8000) >> 15;
  80252. var e = (value & 0x7C00) >> 10;
  80253. var f = value & 0x03FF;
  80254. if (e === 0) {
  80255. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80256. }
  80257. else if (e == 0x1F) {
  80258. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80259. }
  80260. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80261. };
  80262. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80263. var destArray = new Float32Array(dataLength);
  80264. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80265. var index = 0;
  80266. for (var y = 0; y < height; y++) {
  80267. for (var x = 0; x < width; x++) {
  80268. var srcPos = (x + y * width) * 4;
  80269. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80270. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80271. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80272. if (DDSTools.StoreLODInAlphaChannel) {
  80273. destArray[index + 3] = lod;
  80274. }
  80275. else {
  80276. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80277. }
  80278. index += 4;
  80279. }
  80280. }
  80281. return destArray;
  80282. };
  80283. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80284. if (DDSTools.StoreLODInAlphaChannel) {
  80285. var destArray = new Uint16Array(dataLength);
  80286. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80287. var index = 0;
  80288. for (var y = 0; y < height; y++) {
  80289. for (var x = 0; x < width; x++) {
  80290. var srcPos = (x + y * width) * 4;
  80291. destArray[index] = srcData[srcPos];
  80292. destArray[index + 1] = srcData[srcPos + 1];
  80293. destArray[index + 2] = srcData[srcPos + 2];
  80294. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80295. index += 4;
  80296. }
  80297. }
  80298. return destArray;
  80299. }
  80300. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80301. };
  80302. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80303. if (DDSTools.StoreLODInAlphaChannel) {
  80304. var destArray = new Float32Array(dataLength);
  80305. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80306. var index = 0;
  80307. for (var y = 0; y < height; y++) {
  80308. for (var x = 0; x < width; x++) {
  80309. var srcPos = (x + y * width) * 4;
  80310. destArray[index] = srcData[srcPos];
  80311. destArray[index + 1] = srcData[srcPos + 1];
  80312. destArray[index + 2] = srcData[srcPos + 2];
  80313. destArray[index + 3] = lod;
  80314. index += 4;
  80315. }
  80316. }
  80317. return destArray;
  80318. }
  80319. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80320. };
  80321. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80322. var destArray = new Uint8Array(dataLength);
  80323. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80324. var index = 0;
  80325. for (var y = 0; y < height; y++) {
  80326. for (var x = 0; x < width; x++) {
  80327. var srcPos = (x + y * width) * 4;
  80328. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80329. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80330. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80331. if (DDSTools.StoreLODInAlphaChannel) {
  80332. destArray[index + 3] = lod;
  80333. }
  80334. else {
  80335. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80336. }
  80337. index += 4;
  80338. }
  80339. }
  80340. return destArray;
  80341. };
  80342. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80343. var destArray = new Uint8Array(dataLength);
  80344. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80345. var index = 0;
  80346. for (var y = 0; y < height; y++) {
  80347. for (var x = 0; x < width; x++) {
  80348. var srcPos = (x + y * width) * 4;
  80349. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80350. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80351. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80352. if (DDSTools.StoreLODInAlphaChannel) {
  80353. destArray[index + 3] = lod;
  80354. }
  80355. else {
  80356. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80357. }
  80358. index += 4;
  80359. }
  80360. }
  80361. return destArray;
  80362. };
  80363. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80364. var byteArray = new Uint8Array(dataLength);
  80365. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80366. var index = 0;
  80367. for (var y = 0; y < height; y++) {
  80368. for (var x = 0; x < width; x++) {
  80369. var srcPos = (x + y * width) * 4;
  80370. byteArray[index] = srcData[srcPos + rOffset];
  80371. byteArray[index + 1] = srcData[srcPos + gOffset];
  80372. byteArray[index + 2] = srcData[srcPos + bOffset];
  80373. byteArray[index + 3] = srcData[srcPos + aOffset];
  80374. index += 4;
  80375. }
  80376. }
  80377. return byteArray;
  80378. };
  80379. DDSTools._ExtractLongWordOrder = function (value) {
  80380. if (value === 0 || value === 255 || value === -16777216) {
  80381. return 0;
  80382. }
  80383. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80384. };
  80385. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80386. var byteArray = new Uint8Array(dataLength);
  80387. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80388. var index = 0;
  80389. for (var y = 0; y < height; y++) {
  80390. for (var x = 0; x < width; x++) {
  80391. var srcPos = (x + y * width) * 3;
  80392. byteArray[index] = srcData[srcPos + rOffset];
  80393. byteArray[index + 1] = srcData[srcPos + gOffset];
  80394. byteArray[index + 2] = srcData[srcPos + bOffset];
  80395. index += 3;
  80396. }
  80397. }
  80398. return byteArray;
  80399. };
  80400. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80401. var byteArray = new Uint8Array(dataLength);
  80402. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80403. var index = 0;
  80404. for (var y = 0; y < height; y++) {
  80405. for (var x = 0; x < width; x++) {
  80406. var srcPos = (x + y * width);
  80407. byteArray[index] = srcData[srcPos];
  80408. index++;
  80409. }
  80410. }
  80411. return byteArray;
  80412. };
  80413. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80414. if (lodIndex === void 0) { lodIndex = -1; }
  80415. var ext = engine.getCaps().s3tc;
  80416. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80417. var fourCC, width, height, dataLength = 0, dataOffset;
  80418. var byteArray, mipmapCount, mip;
  80419. var internalFormat = 0;
  80420. var format = 0;
  80421. var blockBytes = 1;
  80422. if (header[off_magic] !== DDS_MAGIC) {
  80423. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80424. return;
  80425. }
  80426. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80427. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80428. return;
  80429. }
  80430. if (info.isCompressed && !ext) {
  80431. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80432. return;
  80433. }
  80434. var bpp = header[off_RGBbpp];
  80435. dataOffset = header[off_size] + 4;
  80436. var computeFormats = false;
  80437. if (info.isFourCC) {
  80438. fourCC = header[off_pfFourCC];
  80439. switch (fourCC) {
  80440. case FOURCC_DXT1:
  80441. blockBytes = 8;
  80442. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80443. break;
  80444. case FOURCC_DXT3:
  80445. blockBytes = 16;
  80446. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80447. break;
  80448. case FOURCC_DXT5:
  80449. blockBytes = 16;
  80450. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80451. break;
  80452. case FOURCC_D3DFMT_R16G16B16A16F:
  80453. computeFormats = true;
  80454. break;
  80455. case FOURCC_D3DFMT_R32G32B32A32F:
  80456. computeFormats = true;
  80457. break;
  80458. case FOURCC_DX10:
  80459. // There is an additionnal header so dataOffset need to be changed
  80460. dataOffset += 5 * 4; // 5 uints
  80461. var supported = false;
  80462. switch (info.dxgiFormat) {
  80463. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80464. computeFormats = true;
  80465. supported = true;
  80466. break;
  80467. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80468. info.isRGB = true;
  80469. info.isFourCC = false;
  80470. bpp = 32;
  80471. supported = true;
  80472. break;
  80473. }
  80474. if (supported) {
  80475. break;
  80476. }
  80477. default:
  80478. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80479. return;
  80480. }
  80481. }
  80482. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80483. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80484. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80485. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80486. if (computeFormats) {
  80487. format = engine._getWebGLTextureType(info.textureType);
  80488. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80489. }
  80490. mipmapCount = 1;
  80491. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80492. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80493. }
  80494. for (var face = 0; face < faces; face++) {
  80495. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80496. width = header[off_width];
  80497. height = header[off_height];
  80498. for (mip = 0; mip < mipmapCount; ++mip) {
  80499. if (lodIndex === -1 || lodIndex === mip) {
  80500. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80501. var i = (lodIndex === -1) ? mip : 0;
  80502. if (!info.isCompressed && info.isFourCC) {
  80503. dataLength = width * height * 4;
  80504. var floatArray = null;
  80505. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80506. if (bpp === 128) {
  80507. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80508. }
  80509. else if (bpp === 64) {
  80510. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80511. }
  80512. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80513. format = engine._getWebGLTextureType(info.textureType);
  80514. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80515. }
  80516. else {
  80517. if (bpp === 128) {
  80518. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80519. }
  80520. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80521. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80522. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80523. format = engine._getWebGLTextureType(info.textureType);
  80524. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80525. }
  80526. else {
  80527. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80528. }
  80529. }
  80530. if (floatArray) {
  80531. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80532. }
  80533. }
  80534. else if (info.isRGB) {
  80535. if (bpp === 24) {
  80536. dataLength = width * height * 3;
  80537. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80538. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80539. }
  80540. else {
  80541. dataLength = width * height * 4;
  80542. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80543. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80544. }
  80545. }
  80546. else if (info.isLuminance) {
  80547. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80548. var unpaddedRowSize = width;
  80549. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80550. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80551. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80552. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80553. }
  80554. else {
  80555. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80556. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80557. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80558. }
  80559. }
  80560. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80561. width *= 0.5;
  80562. height *= 0.5;
  80563. width = Math.max(1.0, width);
  80564. height = Math.max(1.0, height);
  80565. }
  80566. if (currentFace !== undefined) {
  80567. // Loading a single face
  80568. break;
  80569. }
  80570. }
  80571. };
  80572. DDSTools.StoreLODInAlphaChannel = false;
  80573. return DDSTools;
  80574. }());
  80575. BABYLON.DDSTools = DDSTools;
  80576. })(BABYLON || (BABYLON = {}));
  80577. //# sourceMappingURL=babylon.dds.js.map
  80578. "use strict";
  80579. var BABYLON;
  80580. (function (BABYLON) {
  80581. /**
  80582. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80583. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80584. */
  80585. var KhronosTextureContainer = /** @class */ (function () {
  80586. /**
  80587. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80588. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80589. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80590. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80591. */
  80592. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80593. this.arrayBuffer = arrayBuffer;
  80594. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80595. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80596. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80597. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80598. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80599. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80600. BABYLON.Tools.Error("texture missing KTX identifier");
  80601. return;
  80602. }
  80603. // load the reset of the header in native 32 bit int
  80604. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80605. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80606. var oppositeEndianess = header[0] === 0x01020304;
  80607. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80608. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80609. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80610. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80611. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80612. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80613. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80614. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80615. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80616. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80617. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80618. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80619. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80620. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80621. if (this.glType !== 0) {
  80622. BABYLON.Tools.Error("only compressed formats currently supported");
  80623. return;
  80624. }
  80625. else {
  80626. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80627. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80628. }
  80629. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80630. BABYLON.Tools.Error("only 2D textures currently supported");
  80631. return;
  80632. }
  80633. if (this.numberOfArrayElements !== 0) {
  80634. BABYLON.Tools.Error("texture arrays not currently supported");
  80635. return;
  80636. }
  80637. if (this.numberOfFaces !== facesExpected) {
  80638. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80639. return;
  80640. }
  80641. // we now have a completely validated file, so could use existence of loadType as success
  80642. // would need to make this more elaborate & adjust checks above to support more than one load type
  80643. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80644. }
  80645. // not as fast hardware based, but will probably never need to use
  80646. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80647. return ((val & 0xFF) << 24)
  80648. | ((val & 0xFF00) << 8)
  80649. | ((val >> 8) & 0xFF00)
  80650. | ((val >> 24) & 0xFF);
  80651. };
  80652. /**
  80653. * It is assumed that the texture has already been created & is currently bound
  80654. */
  80655. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80656. switch (this.loadType) {
  80657. case KhronosTextureContainer.COMPRESSED_2D:
  80658. this._upload2DCompressedLevels(gl, loadMipmaps);
  80659. break;
  80660. case KhronosTextureContainer.TEX_2D:
  80661. case KhronosTextureContainer.COMPRESSED_3D:
  80662. case KhronosTextureContainer.TEX_3D:
  80663. }
  80664. };
  80665. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80666. // initialize width & height for level 1
  80667. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80668. var width = this.pixelWidth;
  80669. var height = this.pixelHeight;
  80670. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80671. for (var level = 0; level < mipmapCount; level++) {
  80672. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80673. for (var face = 0; face < this.numberOfFaces; face++) {
  80674. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80675. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80676. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80677. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80678. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80679. }
  80680. width = Math.max(1.0, width * 0.5);
  80681. height = Math.max(1.0, height * 0.5);
  80682. }
  80683. };
  80684. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80685. // load types
  80686. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80687. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80688. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80689. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80690. return KhronosTextureContainer;
  80691. }());
  80692. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80693. })(BABYLON || (BABYLON = {}));
  80694. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80695. "use strict";
  80696. var BABYLON;
  80697. (function (BABYLON) {
  80698. var Debug = /** @class */ (function () {
  80699. function Debug() {
  80700. }
  80701. Debug.AxesViewer = /** @class */ (function () {
  80702. function AxesViewer(scene, scaleLines) {
  80703. if (scaleLines === void 0) { scaleLines = 1; }
  80704. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80705. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80706. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80707. this.scaleLines = 1;
  80708. this.scaleLines = scaleLines;
  80709. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80710. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80711. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80712. this._xmesh.renderingGroupId = 2;
  80713. this._ymesh.renderingGroupId = 2;
  80714. this._zmesh.renderingGroupId = 2;
  80715. this._xmesh.material.checkReadyOnlyOnce = true;
  80716. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80717. this._ymesh.material.checkReadyOnlyOnce = true;
  80718. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80719. this._zmesh.material.checkReadyOnlyOnce = true;
  80720. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80721. this.scene = scene;
  80722. }
  80723. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80724. var scaleLines = this.scaleLines;
  80725. if (this._xmesh) {
  80726. this._xmesh.position.copyFrom(position);
  80727. }
  80728. if (this._ymesh) {
  80729. this._ymesh.position.copyFrom(position);
  80730. }
  80731. if (this._zmesh) {
  80732. this._zmesh.position.copyFrom(position);
  80733. }
  80734. var point2 = this._xline[1];
  80735. point2.x = xaxis.x * scaleLines;
  80736. point2.y = xaxis.y * scaleLines;
  80737. point2.z = xaxis.z * scaleLines;
  80738. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80739. point2 = this._yline[1];
  80740. point2.x = yaxis.x * scaleLines;
  80741. point2.y = yaxis.y * scaleLines;
  80742. point2.z = yaxis.z * scaleLines;
  80743. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80744. point2 = this._zline[1];
  80745. point2.x = zaxis.x * scaleLines;
  80746. point2.y = zaxis.y * scaleLines;
  80747. point2.z = zaxis.z * scaleLines;
  80748. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80749. };
  80750. AxesViewer.prototype.dispose = function () {
  80751. if (this._xmesh) {
  80752. this._xmesh.dispose();
  80753. }
  80754. if (this._ymesh) {
  80755. this._ymesh.dispose();
  80756. }
  80757. if (this._zmesh) {
  80758. this._zmesh.dispose();
  80759. }
  80760. this._xmesh = null;
  80761. this._ymesh = null;
  80762. this._zmesh = null;
  80763. this.scene = null;
  80764. };
  80765. return AxesViewer;
  80766. }());
  80767. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80768. __extends(BoneAxesViewer, _super);
  80769. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80770. if (scaleLines === void 0) { scaleLines = 1; }
  80771. var _this = _super.call(this, scene, scaleLines) || this;
  80772. _this.pos = BABYLON.Vector3.Zero();
  80773. _this.xaxis = BABYLON.Vector3.Zero();
  80774. _this.yaxis = BABYLON.Vector3.Zero();
  80775. _this.zaxis = BABYLON.Vector3.Zero();
  80776. _this.mesh = mesh;
  80777. _this.bone = bone;
  80778. return _this;
  80779. }
  80780. BoneAxesViewer.prototype.update = function () {
  80781. if (!this.mesh || !this.bone) {
  80782. return;
  80783. }
  80784. var bone = this.bone;
  80785. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80786. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80787. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80788. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80789. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80790. };
  80791. BoneAxesViewer.prototype.dispose = function () {
  80792. if (this.mesh) {
  80793. this.mesh = null;
  80794. this.bone = null;
  80795. _super.prototype.dispose.call(this);
  80796. }
  80797. };
  80798. return BoneAxesViewer;
  80799. }(Debug.AxesViewer));
  80800. Debug.PhysicsViewer = /** @class */ (function () {
  80801. function PhysicsViewer(scene) {
  80802. this._impostors = [];
  80803. this._meshes = [];
  80804. this._numMeshes = 0;
  80805. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80806. var physicEngine = this._scene.getPhysicsEngine();
  80807. if (physicEngine) {
  80808. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80809. }
  80810. }
  80811. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80812. var plugin = this._physicsEnginePlugin;
  80813. for (var i = 0; i < this._numMeshes; i++) {
  80814. var impostor = this._impostors[i];
  80815. if (!impostor) {
  80816. continue;
  80817. }
  80818. if (impostor.isDisposed) {
  80819. this.hideImpostor(this._impostors[i--]);
  80820. }
  80821. else {
  80822. var mesh = this._meshes[i];
  80823. if (mesh && plugin) {
  80824. plugin.syncMeshWithImpostor(mesh, impostor);
  80825. }
  80826. }
  80827. }
  80828. };
  80829. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80830. if (!this._scene) {
  80831. return;
  80832. }
  80833. for (var i = 0; i < this._numMeshes; i++) {
  80834. if (this._impostors[i] == impostor) {
  80835. return;
  80836. }
  80837. }
  80838. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80839. if (debugMesh) {
  80840. this._impostors[this._numMeshes] = impostor;
  80841. this._meshes[this._numMeshes] = debugMesh;
  80842. if (this._numMeshes === 0) {
  80843. this._renderFunction = this._updateDebugMeshes.bind(this);
  80844. this._scene.registerBeforeRender(this._renderFunction);
  80845. }
  80846. this._numMeshes++;
  80847. }
  80848. };
  80849. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80850. if (!impostor || !this._scene) {
  80851. return;
  80852. }
  80853. var removed = false;
  80854. for (var i = 0; i < this._numMeshes; i++) {
  80855. if (this._impostors[i] == impostor) {
  80856. var mesh = this._meshes[i];
  80857. if (!mesh) {
  80858. continue;
  80859. }
  80860. this._scene.removeMesh(mesh);
  80861. mesh.dispose();
  80862. this._numMeshes--;
  80863. if (this._numMeshes > 0) {
  80864. this._meshes[i] = this._meshes[this._numMeshes];
  80865. this._impostors[i] = this._impostors[this._numMeshes];
  80866. this._meshes[this._numMeshes] = null;
  80867. this._impostors[this._numMeshes] = null;
  80868. }
  80869. else {
  80870. this._meshes[0] = null;
  80871. this._impostors[0] = null;
  80872. }
  80873. removed = true;
  80874. break;
  80875. }
  80876. }
  80877. if (removed && this._numMeshes === 0) {
  80878. this._scene.unregisterBeforeRender(this._renderFunction);
  80879. }
  80880. };
  80881. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80882. if (!this._debugMaterial) {
  80883. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80884. this._debugMaterial.wireframe = true;
  80885. }
  80886. return this._debugMaterial;
  80887. };
  80888. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80889. if (!this._debugBoxMesh) {
  80890. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80891. this._debugBoxMesh.renderingGroupId = 1;
  80892. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80893. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80894. scene.removeMesh(this._debugBoxMesh);
  80895. }
  80896. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80897. };
  80898. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80899. if (!this._debugSphereMesh) {
  80900. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80901. this._debugSphereMesh.renderingGroupId = 1;
  80902. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80903. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80904. scene.removeMesh(this._debugSphereMesh);
  80905. }
  80906. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80907. };
  80908. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80909. var mesh = null;
  80910. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80911. mesh = this._getDebugBoxMesh(scene);
  80912. impostor.getBoxSizeToRef(mesh.scaling);
  80913. }
  80914. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80915. mesh = this._getDebugSphereMesh(scene);
  80916. var radius = impostor.getRadius();
  80917. mesh.scaling.x = radius * 2;
  80918. mesh.scaling.y = radius * 2;
  80919. mesh.scaling.z = radius * 2;
  80920. }
  80921. return mesh;
  80922. };
  80923. PhysicsViewer.prototype.dispose = function () {
  80924. for (var i = 0; i < this._numMeshes; i++) {
  80925. this.hideImpostor(this._impostors[i]);
  80926. }
  80927. if (this._debugBoxMesh) {
  80928. this._debugBoxMesh.dispose();
  80929. }
  80930. if (this._debugSphereMesh) {
  80931. this._debugSphereMesh.dispose();
  80932. }
  80933. if (this._debugMaterial) {
  80934. this._debugMaterial.dispose();
  80935. }
  80936. this._impostors.length = 0;
  80937. this._scene = null;
  80938. this._physicsEnginePlugin = null;
  80939. };
  80940. return PhysicsViewer;
  80941. }());
  80942. Debug.SkeletonViewer = /** @class */ (function () {
  80943. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80944. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80945. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80946. this.skeleton = skeleton;
  80947. this.mesh = mesh;
  80948. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80949. this.renderingGroupId = renderingGroupId;
  80950. this.color = BABYLON.Color3.White();
  80951. this._debugLines = new Array();
  80952. this._isEnabled = false;
  80953. this._scene = scene;
  80954. this.update();
  80955. this._renderFunction = this.update.bind(this);
  80956. }
  80957. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80958. get: function () {
  80959. return this._isEnabled;
  80960. },
  80961. set: function (value) {
  80962. if (this._isEnabled === value) {
  80963. return;
  80964. }
  80965. this._isEnabled = value;
  80966. if (value) {
  80967. this._scene.registerBeforeRender(this._renderFunction);
  80968. }
  80969. else {
  80970. this._scene.unregisterBeforeRender(this._renderFunction);
  80971. }
  80972. },
  80973. enumerable: true,
  80974. configurable: true
  80975. });
  80976. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80977. if (x === void 0) { x = 0; }
  80978. if (y === void 0) { y = 0; }
  80979. if (z === void 0) { z = 0; }
  80980. var tmat = BABYLON.Tmp.Matrix[0];
  80981. var parentBone = bone.getParent();
  80982. tmat.copyFrom(bone.getLocalMatrix());
  80983. if (x !== 0 || y !== 0 || z !== 0) {
  80984. var tmat2 = BABYLON.Tmp.Matrix[1];
  80985. BABYLON.Matrix.IdentityToRef(tmat2);
  80986. tmat2.m[12] = x;
  80987. tmat2.m[13] = y;
  80988. tmat2.m[14] = z;
  80989. tmat2.multiplyToRef(tmat, tmat);
  80990. }
  80991. if (parentBone) {
  80992. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80993. }
  80994. tmat.multiplyToRef(meshMat, tmat);
  80995. position.x = tmat.m[12];
  80996. position.y = tmat.m[13];
  80997. position.z = tmat.m[14];
  80998. };
  80999. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  81000. var len = bones.length;
  81001. var meshPos = this.mesh.position;
  81002. for (var i = 0; i < len; i++) {
  81003. var bone = bones[i];
  81004. var points = this._debugLines[i];
  81005. if (!points) {
  81006. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81007. this._debugLines[i] = points;
  81008. }
  81009. this._getBonePosition(points[0], bone, meshMat);
  81010. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  81011. points[0].subtractInPlace(meshPos);
  81012. points[1].subtractInPlace(meshPos);
  81013. }
  81014. };
  81015. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  81016. var len = bones.length;
  81017. var boneNum = 0;
  81018. var meshPos = this.mesh.position;
  81019. for (var i = len - 1; i >= 0; i--) {
  81020. var childBone = bones[i];
  81021. var parentBone = childBone.getParent();
  81022. if (!parentBone) {
  81023. continue;
  81024. }
  81025. var points = this._debugLines[boneNum];
  81026. if (!points) {
  81027. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81028. this._debugLines[boneNum] = points;
  81029. }
  81030. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  81031. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  81032. points[0].subtractInPlace(meshPos);
  81033. points[1].subtractInPlace(meshPos);
  81034. boneNum++;
  81035. }
  81036. };
  81037. SkeletonViewer.prototype.update = function () {
  81038. if (this.autoUpdateBonesMatrices) {
  81039. this.skeleton.computeAbsoluteTransforms();
  81040. }
  81041. if (this.skeleton.bones[0].length === undefined) {
  81042. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  81043. }
  81044. else {
  81045. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  81046. }
  81047. if (!this._debugMesh) {
  81048. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  81049. this._debugMesh.renderingGroupId = this.renderingGroupId;
  81050. }
  81051. else {
  81052. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  81053. }
  81054. this._debugMesh.position.copyFrom(this.mesh.position);
  81055. this._debugMesh.color = this.color;
  81056. };
  81057. SkeletonViewer.prototype.dispose = function () {
  81058. if (this._debugMesh) {
  81059. this.isEnabled = false;
  81060. this._debugMesh.dispose();
  81061. this._debugMesh = null;
  81062. }
  81063. };
  81064. return SkeletonViewer;
  81065. }());
  81066. return Debug;
  81067. }());
  81068. BABYLON.Debug = Debug;
  81069. })(BABYLON || (BABYLON = {}));
  81070. //# sourceMappingURL=babylon.debugModules.js.map
  81071. "use strict";
  81072. var BABYLON;
  81073. (function (BABYLON) {
  81074. var RayHelper = /** @class */ (function () {
  81075. function RayHelper(ray) {
  81076. this.ray = ray;
  81077. }
  81078. RayHelper.CreateAndShow = function (ray, scene, color) {
  81079. var helper = new RayHelper(ray);
  81080. helper.show(scene, color);
  81081. return helper;
  81082. };
  81083. RayHelper.prototype.show = function (scene, color) {
  81084. if (!this._renderFunction && this.ray) {
  81085. var ray = this.ray;
  81086. this._renderFunction = this._render.bind(this);
  81087. this._scene = scene;
  81088. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  81089. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  81090. if (this._renderFunction) {
  81091. this._scene.registerBeforeRender(this._renderFunction);
  81092. }
  81093. }
  81094. if (color && this._renderLine) {
  81095. this._renderLine.color.copyFrom(color);
  81096. }
  81097. };
  81098. RayHelper.prototype.hide = function () {
  81099. if (this._renderFunction && this._scene) {
  81100. this._scene.unregisterBeforeRender(this._renderFunction);
  81101. this._scene = null;
  81102. this._renderFunction = null;
  81103. if (this._renderLine) {
  81104. this._renderLine.dispose();
  81105. this._renderLine = null;
  81106. }
  81107. this._renderPoints = [];
  81108. }
  81109. };
  81110. RayHelper.prototype._render = function () {
  81111. var ray = this.ray;
  81112. if (!ray) {
  81113. return;
  81114. }
  81115. var point = this._renderPoints[1];
  81116. var len = Math.min(ray.length, 1000000);
  81117. point.copyFrom(ray.direction);
  81118. point.scaleInPlace(len);
  81119. point.addInPlace(ray.origin);
  81120. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  81121. };
  81122. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  81123. this._attachedToMesh = mesh;
  81124. var ray = this.ray;
  81125. if (!ray) {
  81126. return;
  81127. }
  81128. if (!ray.direction) {
  81129. ray.direction = BABYLON.Vector3.Zero();
  81130. }
  81131. if (!ray.origin) {
  81132. ray.origin = BABYLON.Vector3.Zero();
  81133. }
  81134. if (length) {
  81135. ray.length = length;
  81136. }
  81137. if (!meshSpaceOrigin) {
  81138. meshSpaceOrigin = BABYLON.Vector3.Zero();
  81139. }
  81140. if (!meshSpaceDirection) {
  81141. // -1 so that this will work with Mesh.lookAt
  81142. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  81143. }
  81144. if (!this._meshSpaceDirection) {
  81145. this._meshSpaceDirection = meshSpaceDirection.clone();
  81146. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  81147. }
  81148. else {
  81149. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  81150. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  81151. }
  81152. if (!this._updateToMeshFunction) {
  81153. this._updateToMeshFunction = this._updateToMesh.bind(this);
  81154. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  81155. }
  81156. this._updateToMesh();
  81157. };
  81158. RayHelper.prototype.detachFromMesh = function () {
  81159. if (this._attachedToMesh) {
  81160. if (this._updateToMeshFunction) {
  81161. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  81162. }
  81163. this._attachedToMesh = null;
  81164. this._updateToMeshFunction = null;
  81165. }
  81166. };
  81167. RayHelper.prototype._updateToMesh = function () {
  81168. var ray = this.ray;
  81169. if (!this._attachedToMesh || !ray) {
  81170. return;
  81171. }
  81172. if (this._attachedToMesh._isDisposed) {
  81173. this.detachFromMesh();
  81174. return;
  81175. }
  81176. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  81177. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  81178. };
  81179. RayHelper.prototype.dispose = function () {
  81180. this.hide();
  81181. this.detachFromMesh();
  81182. this.ray = null;
  81183. };
  81184. return RayHelper;
  81185. }());
  81186. BABYLON.RayHelper = RayHelper;
  81187. })(BABYLON || (BABYLON = {}));
  81188. //# sourceMappingURL=babylon.rayHelper.js.map
  81189. "use strict";
  81190. var BABYLON;
  81191. (function (BABYLON) {
  81192. // load the inspector using require, if not present in the global namespace.
  81193. var DebugLayer = /** @class */ (function () {
  81194. function DebugLayer(scene) {
  81195. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81196. this._scene = scene;
  81197. // load inspector using require, if it doesn't exist on the global namespace.
  81198. }
  81199. /** Creates the inspector window. */
  81200. DebugLayer.prototype._createInspector = function (config) {
  81201. if (config === void 0) { config = {}; }
  81202. var popup = config.popup || false;
  81203. var initialTab = config.initialTab || 0;
  81204. var parentElement = config.parentElement || null;
  81205. if (!this._inspector) {
  81206. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81207. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  81208. } // else nothing to do,; instance is already existing
  81209. };
  81210. DebugLayer.prototype.isVisible = function () {
  81211. if (!this._inspector) {
  81212. return false;
  81213. }
  81214. return true;
  81215. };
  81216. DebugLayer.prototype.hide = function () {
  81217. if (this._inspector) {
  81218. try {
  81219. this._inspector.dispose();
  81220. }
  81221. catch (e) {
  81222. // If the inspector has been removed directly from the inspector tool
  81223. }
  81224. this._inspector = null;
  81225. }
  81226. };
  81227. DebugLayer.prototype.show = function (config) {
  81228. if (config === void 0) { config = {}; }
  81229. if (typeof this.BJSINSPECTOR == 'undefined') {
  81230. // Load inspector and add it to the DOM
  81231. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  81232. }
  81233. else {
  81234. // Otherwise creates the inspector
  81235. this._createInspector(config);
  81236. }
  81237. };
  81238. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  81239. return DebugLayer;
  81240. }());
  81241. BABYLON.DebugLayer = DebugLayer;
  81242. })(BABYLON || (BABYLON = {}));
  81243. //# sourceMappingURL=babylon.debugLayer.js.map
  81244. "use strict";
  81245. var BABYLON;
  81246. (function (BABYLON) {
  81247. var BoundingBoxRenderer = /** @class */ (function () {
  81248. function BoundingBoxRenderer(scene) {
  81249. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81250. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81251. this.showBackLines = true;
  81252. this.renderList = new BABYLON.SmartArray(32);
  81253. this._vertexBuffers = {};
  81254. this._scene = scene;
  81255. }
  81256. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81257. if (this._colorShader) {
  81258. return;
  81259. }
  81260. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81261. attributes: [BABYLON.VertexBuffer.PositionKind],
  81262. uniforms: ["world", "viewProjection", "color"]
  81263. });
  81264. var engine = this._scene.getEngine();
  81265. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81266. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81267. this._createIndexBuffer();
  81268. };
  81269. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81270. var engine = this._scene.getEngine();
  81271. 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]);
  81272. };
  81273. BoundingBoxRenderer.prototype._rebuild = function () {
  81274. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81275. if (vb) {
  81276. vb._rebuild();
  81277. }
  81278. this._createIndexBuffer();
  81279. };
  81280. BoundingBoxRenderer.prototype.reset = function () {
  81281. this.renderList.reset();
  81282. };
  81283. BoundingBoxRenderer.prototype.render = function () {
  81284. if (this.renderList.length === 0) {
  81285. return;
  81286. }
  81287. this._prepareRessources();
  81288. if (!this._colorShader.isReady()) {
  81289. return;
  81290. }
  81291. var engine = this._scene.getEngine();
  81292. engine.setDepthWrite(false);
  81293. this._colorShader._preBind();
  81294. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81295. var boundingBox = this.renderList.data[boundingBoxIndex];
  81296. var min = boundingBox.minimum;
  81297. var max = boundingBox.maximum;
  81298. var diff = max.subtract(min);
  81299. var median = min.add(diff.scale(0.5));
  81300. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81301. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81302. .multiply(boundingBox.getWorldMatrix());
  81303. // VBOs
  81304. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81305. if (this.showBackLines) {
  81306. // Back
  81307. engine.setDepthFunctionToGreaterOrEqual();
  81308. this._scene.resetCachedMaterial();
  81309. this._colorShader.setColor4("color", this.backColor.toColor4());
  81310. this._colorShader.bind(worldMatrix);
  81311. // Draw order
  81312. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81313. }
  81314. // Front
  81315. engine.setDepthFunctionToLess();
  81316. this._scene.resetCachedMaterial();
  81317. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81318. this._colorShader.bind(worldMatrix);
  81319. // Draw order
  81320. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81321. }
  81322. this._colorShader.unbind();
  81323. engine.setDepthFunctionToLessOrEqual();
  81324. engine.setDepthWrite(true);
  81325. };
  81326. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81327. this._prepareRessources();
  81328. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81329. return;
  81330. }
  81331. var engine = this._scene.getEngine();
  81332. engine.setDepthWrite(false);
  81333. engine.setColorWrite(false);
  81334. this._colorShader._preBind();
  81335. var boundingBox = mesh._boundingInfo.boundingBox;
  81336. var min = boundingBox.minimum;
  81337. var max = boundingBox.maximum;
  81338. var diff = max.subtract(min);
  81339. var median = min.add(diff.scale(0.5));
  81340. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81341. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81342. .multiply(boundingBox.getWorldMatrix());
  81343. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81344. engine.setDepthFunctionToLess();
  81345. this._scene.resetCachedMaterial();
  81346. this._colorShader.bind(worldMatrix);
  81347. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81348. this._colorShader.unbind();
  81349. engine.setDepthFunctionToLessOrEqual();
  81350. engine.setDepthWrite(true);
  81351. engine.setColorWrite(true);
  81352. };
  81353. BoundingBoxRenderer.prototype.dispose = function () {
  81354. if (!this._colorShader) {
  81355. return;
  81356. }
  81357. this.renderList.dispose();
  81358. this._colorShader.dispose();
  81359. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81360. if (buffer) {
  81361. buffer.dispose();
  81362. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81363. }
  81364. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81365. };
  81366. return BoundingBoxRenderer;
  81367. }());
  81368. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81369. })(BABYLON || (BABYLON = {}));
  81370. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81371. "use strict";
  81372. var BABYLON;
  81373. (function (BABYLON) {
  81374. var MorphTarget = /** @class */ (function () {
  81375. function MorphTarget(name, influence) {
  81376. if (influence === void 0) { influence = 0; }
  81377. this.name = name;
  81378. this.animations = new Array();
  81379. this._positions = null;
  81380. this._normals = null;
  81381. this._tangents = null;
  81382. this.onInfluenceChanged = new BABYLON.Observable();
  81383. this.influence = influence;
  81384. }
  81385. Object.defineProperty(MorphTarget.prototype, "influence", {
  81386. get: function () {
  81387. return this._influence;
  81388. },
  81389. set: function (influence) {
  81390. if (this._influence === influence) {
  81391. return;
  81392. }
  81393. var previous = this._influence;
  81394. this._influence = influence;
  81395. if (this.onInfluenceChanged.hasObservers) {
  81396. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81397. }
  81398. },
  81399. enumerable: true,
  81400. configurable: true
  81401. });
  81402. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81403. get: function () {
  81404. return !!this._positions;
  81405. },
  81406. enumerable: true,
  81407. configurable: true
  81408. });
  81409. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81410. get: function () {
  81411. return !!this._normals;
  81412. },
  81413. enumerable: true,
  81414. configurable: true
  81415. });
  81416. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81417. get: function () {
  81418. return !!this._tangents;
  81419. },
  81420. enumerable: true,
  81421. configurable: true
  81422. });
  81423. MorphTarget.prototype.setPositions = function (data) {
  81424. this._positions = data;
  81425. };
  81426. MorphTarget.prototype.getPositions = function () {
  81427. return this._positions;
  81428. };
  81429. MorphTarget.prototype.setNormals = function (data) {
  81430. this._normals = data;
  81431. };
  81432. MorphTarget.prototype.getNormals = function () {
  81433. return this._normals;
  81434. };
  81435. MorphTarget.prototype.setTangents = function (data) {
  81436. this._tangents = data;
  81437. };
  81438. MorphTarget.prototype.getTangents = function () {
  81439. return this._tangents;
  81440. };
  81441. /**
  81442. * Serializes the current target into a Serialization object.
  81443. * Returns the serialized object.
  81444. */
  81445. MorphTarget.prototype.serialize = function () {
  81446. var serializationObject = {};
  81447. serializationObject.name = this.name;
  81448. serializationObject.influence = this.influence;
  81449. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81450. if (this.hasNormals) {
  81451. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81452. }
  81453. if (this.hasTangents) {
  81454. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81455. }
  81456. // Animations
  81457. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81458. return serializationObject;
  81459. };
  81460. // Statics
  81461. MorphTarget.Parse = function (serializationObject) {
  81462. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81463. result.setPositions(serializationObject.positions);
  81464. if (serializationObject.normals) {
  81465. result.setNormals(serializationObject.normals);
  81466. }
  81467. if (serializationObject.tangents) {
  81468. result.setTangents(serializationObject.tangents);
  81469. }
  81470. // Animations
  81471. if (serializationObject.animations) {
  81472. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81473. var parsedAnimation = serializationObject.animations[animationIndex];
  81474. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81475. }
  81476. }
  81477. return result;
  81478. };
  81479. MorphTarget.FromMesh = function (mesh, name, influence) {
  81480. if (!name) {
  81481. name = mesh.name;
  81482. }
  81483. var result = new MorphTarget(name, influence);
  81484. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81485. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81486. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81487. }
  81488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81489. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81490. }
  81491. return result;
  81492. };
  81493. return MorphTarget;
  81494. }());
  81495. BABYLON.MorphTarget = MorphTarget;
  81496. })(BABYLON || (BABYLON = {}));
  81497. //# sourceMappingURL=babylon.morphTarget.js.map
  81498. "use strict";
  81499. var BABYLON;
  81500. (function (BABYLON) {
  81501. var MorphTargetManager = /** @class */ (function () {
  81502. function MorphTargetManager(scene) {
  81503. if (scene === void 0) { scene = null; }
  81504. this._targets = new Array();
  81505. this._targetObservable = new Array();
  81506. this._activeTargets = new BABYLON.SmartArray(16);
  81507. this._supportsNormals = false;
  81508. this._supportsTangents = false;
  81509. this._vertexCount = 0;
  81510. this._uniqueId = 0;
  81511. this._tempInfluences = new Array();
  81512. if (!scene) {
  81513. scene = BABYLON.Engine.LastCreatedScene;
  81514. }
  81515. this._scene = scene;
  81516. if (this._scene) {
  81517. this._scene.morphTargetManagers.push(this);
  81518. this._uniqueId = this._scene.getUniqueId();
  81519. }
  81520. }
  81521. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81522. get: function () {
  81523. return this._uniqueId;
  81524. },
  81525. enumerable: true,
  81526. configurable: true
  81527. });
  81528. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81529. get: function () {
  81530. return this._vertexCount;
  81531. },
  81532. enumerable: true,
  81533. configurable: true
  81534. });
  81535. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81536. get: function () {
  81537. return this._supportsNormals;
  81538. },
  81539. enumerable: true,
  81540. configurable: true
  81541. });
  81542. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81543. get: function () {
  81544. return this._supportsTangents;
  81545. },
  81546. enumerable: true,
  81547. configurable: true
  81548. });
  81549. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81550. get: function () {
  81551. return this._targets.length;
  81552. },
  81553. enumerable: true,
  81554. configurable: true
  81555. });
  81556. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81557. get: function () {
  81558. return this._activeTargets.length;
  81559. },
  81560. enumerable: true,
  81561. configurable: true
  81562. });
  81563. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81564. get: function () {
  81565. return this._influences;
  81566. },
  81567. enumerable: true,
  81568. configurable: true
  81569. });
  81570. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81571. return this._activeTargets.data[index];
  81572. };
  81573. MorphTargetManager.prototype.getTarget = function (index) {
  81574. return this._targets[index];
  81575. };
  81576. MorphTargetManager.prototype.addTarget = function (target) {
  81577. var _this = this;
  81578. this._targets.push(target);
  81579. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81580. _this._syncActiveTargets(needUpdate);
  81581. }));
  81582. this._syncActiveTargets(true);
  81583. };
  81584. MorphTargetManager.prototype.removeTarget = function (target) {
  81585. var index = this._targets.indexOf(target);
  81586. if (index >= 0) {
  81587. this._targets.splice(index, 1);
  81588. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81589. this._syncActiveTargets(true);
  81590. }
  81591. };
  81592. /**
  81593. * Serializes the current manager into a Serialization object.
  81594. * Returns the serialized object.
  81595. */
  81596. MorphTargetManager.prototype.serialize = function () {
  81597. var serializationObject = {};
  81598. serializationObject.id = this.uniqueId;
  81599. serializationObject.targets = [];
  81600. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81601. var target = _a[_i];
  81602. serializationObject.targets.push(target.serialize());
  81603. }
  81604. return serializationObject;
  81605. };
  81606. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81607. var influenceCount = 0;
  81608. this._activeTargets.reset();
  81609. this._supportsNormals = true;
  81610. this._supportsTangents = true;
  81611. this._vertexCount = 0;
  81612. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81613. var target = _a[_i];
  81614. this._activeTargets.push(target);
  81615. this._tempInfluences[influenceCount++] = target.influence;
  81616. var positions = target.getPositions();
  81617. if (positions) {
  81618. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81619. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81620. var vertexCount = positions.length / 3;
  81621. if (this._vertexCount === 0) {
  81622. this._vertexCount = vertexCount;
  81623. }
  81624. else if (this._vertexCount !== vertexCount) {
  81625. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81626. return;
  81627. }
  81628. }
  81629. }
  81630. if (!this._influences || this._influences.length !== influenceCount) {
  81631. this._influences = new Float32Array(influenceCount);
  81632. }
  81633. for (var index = 0; index < influenceCount; index++) {
  81634. this._influences[index] = this._tempInfluences[index];
  81635. }
  81636. if (needUpdate && this._scene) {
  81637. // Flag meshes as dirty to resync with the active targets
  81638. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81639. var mesh = _c[_b];
  81640. if (mesh.morphTargetManager === this) {
  81641. mesh._syncGeometryWithMorphTargetManager();
  81642. }
  81643. }
  81644. }
  81645. };
  81646. // Statics
  81647. MorphTargetManager.Parse = function (serializationObject, scene) {
  81648. var result = new MorphTargetManager(scene);
  81649. result._uniqueId = serializationObject.id;
  81650. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81651. var targetData = _a[_i];
  81652. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81653. }
  81654. return result;
  81655. };
  81656. return MorphTargetManager;
  81657. }());
  81658. BABYLON.MorphTargetManager = MorphTargetManager;
  81659. })(BABYLON || (BABYLON = {}));
  81660. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81661. "use strict";
  81662. var BABYLON;
  81663. (function (BABYLON) {
  81664. var Octree = /** @class */ (function () {
  81665. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81666. if (maxDepth === void 0) { maxDepth = 2; }
  81667. this.maxDepth = maxDepth;
  81668. this.dynamicContent = new Array();
  81669. this._maxBlockCapacity = maxBlockCapacity || 64;
  81670. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81671. this._creationFunc = creationFunc;
  81672. }
  81673. // Methods
  81674. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81675. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81676. };
  81677. Octree.prototype.addMesh = function (entry) {
  81678. for (var index = 0; index < this.blocks.length; index++) {
  81679. var block = this.blocks[index];
  81680. block.addEntry(entry);
  81681. }
  81682. };
  81683. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81684. this._selectionContent.reset();
  81685. for (var index = 0; index < this.blocks.length; index++) {
  81686. var block = this.blocks[index];
  81687. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81688. }
  81689. if (allowDuplicate) {
  81690. this._selectionContent.concat(this.dynamicContent);
  81691. }
  81692. else {
  81693. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81694. }
  81695. return this._selectionContent;
  81696. };
  81697. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81698. this._selectionContent.reset();
  81699. for (var index = 0; index < this.blocks.length; index++) {
  81700. var block = this.blocks[index];
  81701. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81702. }
  81703. if (allowDuplicate) {
  81704. this._selectionContent.concat(this.dynamicContent);
  81705. }
  81706. else {
  81707. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81708. }
  81709. return this._selectionContent;
  81710. };
  81711. Octree.prototype.intersectsRay = function (ray) {
  81712. this._selectionContent.reset();
  81713. for (var index = 0; index < this.blocks.length; index++) {
  81714. var block = this.blocks[index];
  81715. block.intersectsRay(ray, this._selectionContent);
  81716. }
  81717. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81718. return this._selectionContent;
  81719. };
  81720. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81721. target.blocks = new Array();
  81722. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81723. // Segmenting space
  81724. for (var x = 0; x < 2; x++) {
  81725. for (var y = 0; y < 2; y++) {
  81726. for (var z = 0; z < 2; z++) {
  81727. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81728. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81729. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81730. block.addEntries(entries);
  81731. target.blocks.push(block);
  81732. }
  81733. }
  81734. }
  81735. };
  81736. Octree.CreationFuncForMeshes = function (entry, block) {
  81737. var boundingInfo = entry.getBoundingInfo();
  81738. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81739. block.entries.push(entry);
  81740. }
  81741. };
  81742. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81743. var boundingInfo = entry.getBoundingInfo();
  81744. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81745. block.entries.push(entry);
  81746. }
  81747. };
  81748. return Octree;
  81749. }());
  81750. BABYLON.Octree = Octree;
  81751. })(BABYLON || (BABYLON = {}));
  81752. //# sourceMappingURL=babylon.octree.js.map
  81753. "use strict";
  81754. var BABYLON;
  81755. (function (BABYLON) {
  81756. var OctreeBlock = /** @class */ (function () {
  81757. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81758. this.entries = new Array();
  81759. this._boundingVectors = new Array();
  81760. this._capacity = capacity;
  81761. this._depth = depth;
  81762. this._maxDepth = maxDepth;
  81763. this._creationFunc = creationFunc;
  81764. this._minPoint = minPoint;
  81765. this._maxPoint = maxPoint;
  81766. this._boundingVectors.push(minPoint.clone());
  81767. this._boundingVectors.push(maxPoint.clone());
  81768. this._boundingVectors.push(minPoint.clone());
  81769. this._boundingVectors[2].x = maxPoint.x;
  81770. this._boundingVectors.push(minPoint.clone());
  81771. this._boundingVectors[3].y = maxPoint.y;
  81772. this._boundingVectors.push(minPoint.clone());
  81773. this._boundingVectors[4].z = maxPoint.z;
  81774. this._boundingVectors.push(maxPoint.clone());
  81775. this._boundingVectors[5].z = minPoint.z;
  81776. this._boundingVectors.push(maxPoint.clone());
  81777. this._boundingVectors[6].x = minPoint.x;
  81778. this._boundingVectors.push(maxPoint.clone());
  81779. this._boundingVectors[7].y = minPoint.y;
  81780. }
  81781. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81782. // Property
  81783. get: function () {
  81784. return this._capacity;
  81785. },
  81786. enumerable: true,
  81787. configurable: true
  81788. });
  81789. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81790. get: function () {
  81791. return this._minPoint;
  81792. },
  81793. enumerable: true,
  81794. configurable: true
  81795. });
  81796. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81797. get: function () {
  81798. return this._maxPoint;
  81799. },
  81800. enumerable: true,
  81801. configurable: true
  81802. });
  81803. // Methods
  81804. OctreeBlock.prototype.addEntry = function (entry) {
  81805. if (this.blocks) {
  81806. for (var index = 0; index < this.blocks.length; index++) {
  81807. var block = this.blocks[index];
  81808. block.addEntry(entry);
  81809. }
  81810. return;
  81811. }
  81812. this._creationFunc(entry, this);
  81813. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81814. this.createInnerBlocks();
  81815. }
  81816. };
  81817. OctreeBlock.prototype.addEntries = function (entries) {
  81818. for (var index = 0; index < entries.length; index++) {
  81819. var mesh = entries[index];
  81820. this.addEntry(mesh);
  81821. }
  81822. };
  81823. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81824. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81825. if (this.blocks) {
  81826. for (var index = 0; index < this.blocks.length; index++) {
  81827. var block = this.blocks[index];
  81828. block.select(frustumPlanes, selection, allowDuplicate);
  81829. }
  81830. return;
  81831. }
  81832. if (allowDuplicate) {
  81833. selection.concat(this.entries);
  81834. }
  81835. else {
  81836. selection.concatWithNoDuplicate(this.entries);
  81837. }
  81838. }
  81839. };
  81840. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81841. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81842. if (this.blocks) {
  81843. for (var index = 0; index < this.blocks.length; index++) {
  81844. var block = this.blocks[index];
  81845. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81846. }
  81847. return;
  81848. }
  81849. if (allowDuplicate) {
  81850. selection.concat(this.entries);
  81851. }
  81852. else {
  81853. selection.concatWithNoDuplicate(this.entries);
  81854. }
  81855. }
  81856. };
  81857. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81858. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81859. if (this.blocks) {
  81860. for (var index = 0; index < this.blocks.length; index++) {
  81861. var block = this.blocks[index];
  81862. block.intersectsRay(ray, selection);
  81863. }
  81864. return;
  81865. }
  81866. selection.concatWithNoDuplicate(this.entries);
  81867. }
  81868. };
  81869. OctreeBlock.prototype.createInnerBlocks = function () {
  81870. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81871. };
  81872. return OctreeBlock;
  81873. }());
  81874. BABYLON.OctreeBlock = OctreeBlock;
  81875. })(BABYLON || (BABYLON = {}));
  81876. //# sourceMappingURL=babylon.octreeBlock.js.map
  81877. "use strict";
  81878. var BABYLON;
  81879. (function (BABYLON) {
  81880. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81881. __extends(VRDistortionCorrectionPostProcess, _super);
  81882. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81883. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81884. 'LensCenter',
  81885. 'Scale',
  81886. 'ScaleIn',
  81887. 'HmdWarpParam'
  81888. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81889. _this._isRightEye = isRightEye;
  81890. _this._distortionFactors = vrMetrics.distortionK;
  81891. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81892. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81893. _this.adaptScaleToCurrentViewport = true;
  81894. _this.onSizeChangedObservable.add(function () {
  81895. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81896. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81897. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81898. });
  81899. _this.onApplyObservable.add(function (effect) {
  81900. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81901. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81902. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81903. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81904. });
  81905. return _this;
  81906. }
  81907. return VRDistortionCorrectionPostProcess;
  81908. }(BABYLON.PostProcess));
  81909. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81910. })(BABYLON || (BABYLON = {}));
  81911. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81912. "use strict";
  81913. var BABYLON;
  81914. (function (BABYLON) {
  81915. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81916. __extends(AnaglyphPostProcess, _super);
  81917. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81918. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81919. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81920. _this.onApplyObservable.add(function (effect) {
  81921. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81922. });
  81923. return _this;
  81924. }
  81925. return AnaglyphPostProcess;
  81926. }(BABYLON.PostProcess));
  81927. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81928. })(BABYLON || (BABYLON = {}));
  81929. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81930. "use strict";
  81931. var BABYLON;
  81932. (function (BABYLON) {
  81933. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81934. __extends(StereoscopicInterlacePostProcess, _super);
  81935. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81936. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81937. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81938. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81939. _this.onSizeChangedObservable.add(function () {
  81940. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81941. });
  81942. _this.onApplyObservable.add(function (effect) {
  81943. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81944. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81945. });
  81946. return _this;
  81947. }
  81948. return StereoscopicInterlacePostProcess;
  81949. }(BABYLON.PostProcess));
  81950. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81951. })(BABYLON || (BABYLON = {}));
  81952. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81953. "use strict";
  81954. var BABYLON;
  81955. (function (BABYLON) {
  81956. /**
  81957. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81958. * Screen rotation is taken into account.
  81959. */
  81960. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81961. function FreeCameraDeviceOrientationInput() {
  81962. var _this = this;
  81963. this._screenOrientationAngle = 0;
  81964. this._screenQuaternion = new BABYLON.Quaternion();
  81965. this._alpha = 0;
  81966. this._beta = 0;
  81967. this._gamma = 0;
  81968. this._orientationChanged = function () {
  81969. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81970. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81971. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81972. };
  81973. this._deviceOrientation = function (evt) {
  81974. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81975. _this._beta = evt.beta !== null ? evt.beta : 0;
  81976. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81977. };
  81978. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81979. this._orientationChanged();
  81980. }
  81981. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81982. get: function () {
  81983. return this._camera;
  81984. },
  81985. set: function (camera) {
  81986. this._camera = camera;
  81987. if (this._camera != null && !this._camera.rotationQuaternion) {
  81988. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81989. }
  81990. },
  81991. enumerable: true,
  81992. configurable: true
  81993. });
  81994. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81995. window.addEventListener("orientationchange", this._orientationChanged);
  81996. window.addEventListener("deviceorientation", this._deviceOrientation);
  81997. //In certain cases, the attach control is called AFTER orientation was changed,
  81998. //So this is needed.
  81999. this._orientationChanged();
  82000. };
  82001. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  82002. window.removeEventListener("orientationchange", this._orientationChanged);
  82003. window.removeEventListener("deviceorientation", this._deviceOrientation);
  82004. };
  82005. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  82006. //if no device orientation provided, don't update the rotation.
  82007. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  82008. if (!this._alpha)
  82009. return;
  82010. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  82011. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  82012. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  82013. //Mirror on XY Plane
  82014. this._camera.rotationQuaternion.z *= -1;
  82015. this._camera.rotationQuaternion.w *= -1;
  82016. };
  82017. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  82018. return "FreeCameraDeviceOrientationInput";
  82019. };
  82020. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  82021. return "deviceOrientation";
  82022. };
  82023. return FreeCameraDeviceOrientationInput;
  82024. }());
  82025. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  82026. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  82027. })(BABYLON || (BABYLON = {}));
  82028. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  82029. "use strict";
  82030. var BABYLON;
  82031. (function (BABYLON) {
  82032. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  82033. function ArcRotateCameraVRDeviceOrientationInput() {
  82034. this.alphaCorrection = 1;
  82035. this.betaCorrection = 1;
  82036. this.gammaCorrection = 1;
  82037. this._alpha = 0;
  82038. this._gamma = 0;
  82039. this._dirty = false;
  82040. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  82041. }
  82042. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  82043. this.camera.attachControl(element, noPreventDefault);
  82044. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  82045. };
  82046. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  82047. if (evt.alpha !== null) {
  82048. this._alpha = +evt.alpha | 0;
  82049. }
  82050. if (evt.gamma !== null) {
  82051. this._gamma = +evt.gamma | 0;
  82052. }
  82053. this._dirty = true;
  82054. };
  82055. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  82056. if (this._dirty) {
  82057. this._dirty = false;
  82058. if (this._gamma < 0) {
  82059. this._gamma = 180 + this._gamma;
  82060. }
  82061. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  82062. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  82063. }
  82064. };
  82065. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  82066. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  82067. };
  82068. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  82069. return "ArcRotateCameraVRDeviceOrientationInput";
  82070. };
  82071. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  82072. return "VRDeviceOrientation";
  82073. };
  82074. return ArcRotateCameraVRDeviceOrientationInput;
  82075. }());
  82076. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  82077. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  82078. })(BABYLON || (BABYLON = {}));
  82079. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  82080. "use strict";
  82081. var BABYLON;
  82082. (function (BABYLON) {
  82083. var VRCameraMetrics = /** @class */ (function () {
  82084. function VRCameraMetrics() {
  82085. this.compensateDistortion = true;
  82086. }
  82087. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  82088. get: function () {
  82089. return this.hResolution / (2 * this.vResolution);
  82090. },
  82091. enumerable: true,
  82092. configurable: true
  82093. });
  82094. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  82095. get: function () {
  82096. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  82097. },
  82098. enumerable: true,
  82099. configurable: true
  82100. });
  82101. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  82102. get: function () {
  82103. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82104. var h = (4 * meters) / this.hScreenSize;
  82105. return BABYLON.Matrix.Translation(h, 0, 0);
  82106. },
  82107. enumerable: true,
  82108. configurable: true
  82109. });
  82110. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  82111. get: function () {
  82112. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82113. var h = (4 * meters) / this.hScreenSize;
  82114. return BABYLON.Matrix.Translation(-h, 0, 0);
  82115. },
  82116. enumerable: true,
  82117. configurable: true
  82118. });
  82119. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  82120. get: function () {
  82121. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  82122. },
  82123. enumerable: true,
  82124. configurable: true
  82125. });
  82126. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  82127. get: function () {
  82128. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  82129. },
  82130. enumerable: true,
  82131. configurable: true
  82132. });
  82133. VRCameraMetrics.GetDefault = function () {
  82134. var result = new VRCameraMetrics();
  82135. result.hResolution = 1280;
  82136. result.vResolution = 800;
  82137. result.hScreenSize = 0.149759993;
  82138. result.vScreenSize = 0.0935999975;
  82139. result.vScreenCenter = 0.0467999987;
  82140. result.eyeToScreenDistance = 0.0410000011;
  82141. result.lensSeparationDistance = 0.0635000020;
  82142. result.interpupillaryDistance = 0.0640000030;
  82143. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  82144. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  82145. result.postProcessScaleFactor = 1.714605507808412;
  82146. result.lensCenterOffset = 0.151976421;
  82147. return result;
  82148. };
  82149. return VRCameraMetrics;
  82150. }());
  82151. BABYLON.VRCameraMetrics = VRCameraMetrics;
  82152. })(BABYLON || (BABYLON = {}));
  82153. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  82154. "use strict";
  82155. var BABYLON;
  82156. (function (BABYLON) {
  82157. /**
  82158. * This represents a WebVR camera.
  82159. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  82160. * @example http://doc.babylonjs.com/how_to/webvr_camera
  82161. */
  82162. var WebVRFreeCamera = /** @class */ (function (_super) {
  82163. __extends(WebVRFreeCamera, _super);
  82164. /**
  82165. * Instantiates a WebVRFreeCamera.
  82166. * @param name The name of the WebVRFreeCamera
  82167. * @param position The starting anchor position for the camera
  82168. * @param scene The scene the camera belongs to
  82169. * @param webVROptions a set of customizable options for the webVRCamera
  82170. */
  82171. function WebVRFreeCamera(name, position, scene, webVROptions) {
  82172. if (webVROptions === void 0) { webVROptions = {}; }
  82173. var _this = _super.call(this, name, position, scene) || this;
  82174. _this.webVROptions = webVROptions;
  82175. /**
  82176. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  82177. */
  82178. _this._vrDevice = null;
  82179. /**
  82180. * The rawPose of the vrDevice.
  82181. */
  82182. _this.rawPose = null;
  82183. _this._specsVersion = "1.1";
  82184. _this._attached = false;
  82185. _this._descendants = [];
  82186. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82187. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82188. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  82189. _this._standingMatrix = null;
  82190. /**
  82191. * Represents device position in babylon space.
  82192. */
  82193. _this.devicePosition = BABYLON.Vector3.Zero();
  82194. /**
  82195. * Represents device rotation in babylon space.
  82196. */
  82197. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  82198. /**
  82199. * The scale of the device to be used when translating from device space to babylon space.
  82200. */
  82201. _this.deviceScaleFactor = 1;
  82202. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82203. _this._worldToDevice = BABYLON.Matrix.Identity();
  82204. /**
  82205. * References to the webVR controllers for the vrDevice.
  82206. */
  82207. _this.controllers = [];
  82208. /**
  82209. * Emits an event when a controller is attached.
  82210. */
  82211. _this.onControllersAttachedObservable = new BABYLON.Observable();
  82212. /**
  82213. * Emits an event when a controller's mesh has been loaded;
  82214. */
  82215. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82216. /**
  82217. * If the rig cameras be used as parent instead of this camera.
  82218. */
  82219. _this.rigParenting = true;
  82220. _this._defaultHeight = undefined;
  82221. _this._workingVector = BABYLON.Vector3.Zero();
  82222. _this._oneVector = BABYLON.Vector3.One();
  82223. _this._workingMatrix = BABYLON.Matrix.Identity();
  82224. _this._cache.position = BABYLON.Vector3.Zero();
  82225. if (webVROptions.defaultHeight) {
  82226. _this._defaultHeight = webVROptions.defaultHeight;
  82227. _this.position.y = _this._defaultHeight;
  82228. }
  82229. _this.minZ = 0.1;
  82230. //legacy support - the compensation boolean was removed.
  82231. if (arguments.length === 5) {
  82232. _this.webVROptions = arguments[4];
  82233. }
  82234. // default webVR options
  82235. if (_this.webVROptions.trackPosition == undefined) {
  82236. _this.webVROptions.trackPosition = true;
  82237. }
  82238. if (_this.webVROptions.controllerMeshes == undefined) {
  82239. _this.webVROptions.controllerMeshes = true;
  82240. }
  82241. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  82242. _this.webVROptions.defaultLightingOnControllers = true;
  82243. }
  82244. _this.rotationQuaternion = new BABYLON.Quaternion();
  82245. if (_this.webVROptions && _this.webVROptions.positionScale) {
  82246. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  82247. }
  82248. //enable VR
  82249. var engine = _this.getEngine();
  82250. _this._onVREnabled = function (success) { if (success) {
  82251. _this.initControllers();
  82252. } };
  82253. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82254. engine.initWebVR().add(function (event) {
  82255. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82256. return;
  82257. }
  82258. _this._vrDevice = event.vrDisplay;
  82259. //reset the rig parameters.
  82260. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82261. if (_this._attached) {
  82262. _this.getEngine().enableVR();
  82263. }
  82264. });
  82265. if (typeof (VRFrameData) !== "undefined")
  82266. _this._frameData = new VRFrameData();
  82267. /**
  82268. * The idea behind the following lines:
  82269. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82270. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82271. * the second will not show it correctly.
  82272. *
  82273. * To solve this - each object that has the camera as parent will be added to a protected array.
  82274. * When the rig camera renders, it will take this array and set all of those to be its children.
  82275. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82276. * Amazing!
  82277. */
  82278. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82279. if (camera.parent === _this && _this.rigParenting) {
  82280. _this._descendants = _this.getDescendants(true, function (n) {
  82281. // don't take the cameras or the controllers!
  82282. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82283. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82284. return !isController && !isRigCamera;
  82285. });
  82286. _this._descendants.forEach(function (node) {
  82287. node.parent = camera;
  82288. });
  82289. }
  82290. });
  82291. scene.onAfterCameraRenderObservable.add(function (camera) {
  82292. if (camera.parent === _this && _this.rigParenting) {
  82293. _this._descendants.forEach(function (node) {
  82294. node.parent = _this;
  82295. });
  82296. }
  82297. });
  82298. return _this;
  82299. }
  82300. /**
  82301. * Gets the device distance from the ground in meters.
  82302. * @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.
  82303. */
  82304. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82305. if (this._standingMatrix) {
  82306. // Add standing matrix offset to get real offset from ground in room
  82307. this._standingMatrix.getTranslationToRef(this._workingVector);
  82308. return this._deviceRoomPosition.y + this._workingVector.y;
  82309. }
  82310. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82311. return this._defaultHeight || 0;
  82312. };
  82313. /**
  82314. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82315. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82316. */
  82317. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82318. var _this = this;
  82319. if (callback === void 0) { callback = function (bool) { }; }
  82320. // Use standing matrix if available
  82321. this.getEngine().initWebVRAsync().then(function (result) {
  82322. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82323. callback(false);
  82324. }
  82325. else {
  82326. _this._standingMatrix = new BABYLON.Matrix();
  82327. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82328. if (!_this.getScene().useRightHandedSystem) {
  82329. [2, 6, 8, 9, 14].forEach(function (num) {
  82330. if (_this._standingMatrix) {
  82331. _this._standingMatrix.m[num] *= -1;
  82332. }
  82333. });
  82334. }
  82335. callback(true);
  82336. }
  82337. });
  82338. };
  82339. /**
  82340. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82341. * @returns A promise with a boolean set to if the standing matrix is supported.
  82342. */
  82343. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82344. var _this = this;
  82345. return new Promise(function (res, rej) {
  82346. _this.useStandingMatrix(function (supported) {
  82347. res(supported);
  82348. });
  82349. });
  82350. };
  82351. /**
  82352. * Disposes the camera
  82353. */
  82354. WebVRFreeCamera.prototype.dispose = function () {
  82355. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82356. _super.prototype.dispose.call(this);
  82357. };
  82358. /**
  82359. * Gets a vrController by name.
  82360. * @param name The name of the controller to retreive
  82361. * @returns the controller matching the name specified or null if not found
  82362. */
  82363. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82364. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82365. var gp = _a[_i];
  82366. if (gp.hand === name) {
  82367. return gp;
  82368. }
  82369. }
  82370. return null;
  82371. };
  82372. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82373. /**
  82374. * The controller corrisponding to the users left hand.
  82375. */
  82376. get: function () {
  82377. if (!this._leftController) {
  82378. this._leftController = this.getControllerByName("left");
  82379. }
  82380. return this._leftController;
  82381. },
  82382. enumerable: true,
  82383. configurable: true
  82384. });
  82385. ;
  82386. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82387. /**
  82388. * The controller corrisponding to the users right hand.
  82389. */
  82390. get: function () {
  82391. if (!this._rightController) {
  82392. this._rightController = this.getControllerByName("right");
  82393. }
  82394. return this._rightController;
  82395. },
  82396. enumerable: true,
  82397. configurable: true
  82398. });
  82399. ;
  82400. /**
  82401. * Casts a ray forward from the vrCamera's gaze.
  82402. * @param length Length of the ray (default: 100)
  82403. * @returns the ray corrisponding to the gaze
  82404. */
  82405. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82406. if (length === void 0) { length = 100; }
  82407. if (this.leftCamera) {
  82408. // Use left eye to avoid computation to compute center on every call
  82409. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82410. }
  82411. else {
  82412. return _super.prototype.getForwardRay.call(this, length);
  82413. }
  82414. };
  82415. /**
  82416. * Updates the camera based on device's frame data
  82417. */
  82418. WebVRFreeCamera.prototype._checkInputs = function () {
  82419. if (this._vrDevice && this._vrDevice.isPresenting) {
  82420. this._vrDevice.getFrameData(this._frameData);
  82421. this.updateFromDevice(this._frameData.pose);
  82422. }
  82423. _super.prototype._checkInputs.call(this);
  82424. };
  82425. /**
  82426. * Updates the poseControlled values based on the input device pose.
  82427. * @param poseData Pose coming from the device
  82428. */
  82429. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82430. if (poseData && poseData.orientation) {
  82431. this.rawPose = poseData;
  82432. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82433. if (this.getScene().useRightHandedSystem) {
  82434. this._deviceRoomRotationQuaternion.z *= -1;
  82435. this._deviceRoomRotationQuaternion.w *= -1;
  82436. }
  82437. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82438. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82439. if (this.getScene().useRightHandedSystem) {
  82440. this._deviceRoomPosition.z *= -1;
  82441. }
  82442. }
  82443. }
  82444. };
  82445. /**
  82446. * WebVR's attach control will start broadcasting frames to the device.
  82447. * Note that in certain browsers (chrome for example) this function must be called
  82448. * within a user-interaction callback. Example:
  82449. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82450. *
  82451. * @param element html element to attach the vrDevice to
  82452. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82453. */
  82454. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82455. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82456. this._attached = true;
  82457. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82458. if (this._vrDevice) {
  82459. this.getEngine().enableVR();
  82460. }
  82461. };
  82462. /**
  82463. * Detaches the camera from the html element and disables VR
  82464. *
  82465. * @param element html element to detach from
  82466. */
  82467. WebVRFreeCamera.prototype.detachControl = function (element) {
  82468. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82469. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82470. _super.prototype.detachControl.call(this, element);
  82471. this._attached = false;
  82472. this.getEngine().disableVR();
  82473. };
  82474. /**
  82475. * @returns the name of this class
  82476. */
  82477. WebVRFreeCamera.prototype.getClassName = function () {
  82478. return "WebVRFreeCamera";
  82479. };
  82480. /**
  82481. * Calls resetPose on the vrDisplay
  82482. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82483. */
  82484. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82485. //uses the vrDisplay's "resetPose()".
  82486. //pitch and roll won't be affected.
  82487. this._vrDevice.resetPose();
  82488. };
  82489. /**
  82490. * Updates the rig cameras (left and right eye)
  82491. */
  82492. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82493. var camLeft = this._rigCameras[0];
  82494. var camRight = this._rigCameras[1];
  82495. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82496. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82497. camLeft.position.copyFrom(this._deviceRoomPosition);
  82498. camRight.position.copyFrom(this._deviceRoomPosition);
  82499. };
  82500. /**
  82501. * Updates the cached values of the camera
  82502. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82503. */
  82504. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82505. var _this = this;
  82506. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82507. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82508. if (!this.updateCacheCalled) {
  82509. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82510. this.updateCacheCalled = true;
  82511. this.update();
  82512. }
  82513. // Set working vector to the device position in room space rotated by the new rotation
  82514. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82515. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82516. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82517. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82518. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82519. // Add translation from anchor position
  82520. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82521. this._workingVector.addInPlace(this.position);
  82522. this._workingVector.subtractInPlace(this._cache.position);
  82523. this._deviceToWorld.setTranslation(this._workingVector);
  82524. // Set an inverted matrix to be used when updating the camera
  82525. this._deviceToWorld.invertToRef(this._worldToDevice);
  82526. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82527. this.controllers.forEach(function (controller) {
  82528. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82529. controller.update();
  82530. });
  82531. }
  82532. if (!ignoreParentClass) {
  82533. _super.prototype._updateCache.call(this);
  82534. }
  82535. this.updateCacheCalled = false;
  82536. };
  82537. /**
  82538. * Updates the current device position and rotation in the babylon world
  82539. */
  82540. WebVRFreeCamera.prototype.update = function () {
  82541. // Get current device position in babylon world
  82542. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82543. // Get current device rotation in babylon world
  82544. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82545. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82546. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82547. _super.prototype.update.call(this);
  82548. };
  82549. /**
  82550. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82551. * @returns an identity matrix
  82552. */
  82553. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82554. return BABYLON.Matrix.Identity();
  82555. };
  82556. /**
  82557. * This function is called by the two RIG cameras.
  82558. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82559. */
  82560. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82561. var _this = this;
  82562. // Update the parent camera prior to using a child camera to avoid desynchronization
  82563. var parentCamera = this._cameraRigParams["parentCamera"];
  82564. parentCamera._updateCache();
  82565. //WebVR 1.1
  82566. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82567. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82568. if (!this.getScene().useRightHandedSystem) {
  82569. [2, 6, 8, 9, 14].forEach(function (num) {
  82570. _this._webvrViewMatrix.m[num] *= -1;
  82571. });
  82572. }
  82573. // update the camera rotation matrix
  82574. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82575. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82576. // Computing target and final matrix
  82577. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82578. // should the view matrix be updated with scale and position offset?
  82579. if (parentCamera.deviceScaleFactor !== 1) {
  82580. this._webvrViewMatrix.invert();
  82581. // scale the position, if set
  82582. if (parentCamera.deviceScaleFactor) {
  82583. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82584. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82585. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82586. }
  82587. this._webvrViewMatrix.invert();
  82588. }
  82589. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82590. return this._webvrViewMatrix;
  82591. };
  82592. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82593. var _this = this;
  82594. var parentCamera = this.parent;
  82595. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82596. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82597. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82598. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82599. //babylon compatible matrix
  82600. if (!this.getScene().useRightHandedSystem) {
  82601. [8, 9, 10, 11].forEach(function (num) {
  82602. _this._projectionMatrix.m[num] *= -1;
  82603. });
  82604. }
  82605. return this._projectionMatrix;
  82606. };
  82607. /**
  82608. * Initializes the controllers and their meshes
  82609. */
  82610. WebVRFreeCamera.prototype.initControllers = function () {
  82611. var _this = this;
  82612. this.controllers = [];
  82613. var manager = this.getScene().gamepadManager;
  82614. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82615. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82616. var webVrController = gamepad;
  82617. if (webVrController.defaultModel) {
  82618. webVrController.defaultModel.setEnabled(false);
  82619. }
  82620. if (webVrController.hand === "right") {
  82621. _this._rightController = null;
  82622. }
  82623. if (webVrController.hand === "left") {
  82624. _this._leftController = null;
  82625. }
  82626. var controllerIndex = _this.controllers.indexOf(webVrController);
  82627. if (controllerIndex !== -1) {
  82628. _this.controllers.splice(controllerIndex, 1);
  82629. }
  82630. }
  82631. });
  82632. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82633. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82634. var webVrController_1 = gamepad;
  82635. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82636. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82637. if (_this.webVROptions.controllerMeshes) {
  82638. if (webVrController_1.defaultModel) {
  82639. webVrController_1.defaultModel.setEnabled(true);
  82640. }
  82641. else {
  82642. // Load the meshes
  82643. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82644. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82645. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82646. if (_this.webVROptions.defaultLightingOnControllers) {
  82647. if (!_this._lightOnControllers) {
  82648. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82649. }
  82650. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82651. var children = mesh.getChildren();
  82652. if (children.length !== 0) {
  82653. children.forEach(function (mesh) {
  82654. light.includedOnlyMeshes.push(mesh);
  82655. activateLightOnSubMeshes_1(mesh, light);
  82656. });
  82657. }
  82658. };
  82659. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82660. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82661. }
  82662. });
  82663. }
  82664. }
  82665. webVrController_1.attachToPoseControlledCamera(_this);
  82666. // since this is async - sanity check. Is the controller already stored?
  82667. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82668. //add to the controllers array
  82669. _this.controllers.push(webVrController_1);
  82670. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82671. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82672. // So we're overriding setting left & right manually to be sure
  82673. var firstViveWandDetected = false;
  82674. for (var i = 0; i < _this.controllers.length; i++) {
  82675. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82676. if (!firstViveWandDetected) {
  82677. firstViveWandDetected = true;
  82678. _this.controllers[i].hand = "left";
  82679. }
  82680. else {
  82681. _this.controllers[i].hand = "right";
  82682. }
  82683. }
  82684. }
  82685. //did we find enough controllers? Great! let the developer know.
  82686. if (_this.controllers.length >= 2) {
  82687. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82688. }
  82689. }
  82690. }
  82691. });
  82692. };
  82693. return WebVRFreeCamera;
  82694. }(BABYLON.FreeCamera));
  82695. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82696. })(BABYLON || (BABYLON = {}));
  82697. //# sourceMappingURL=babylon.webVRCamera.js.map
  82698. "use strict";
  82699. var BABYLON;
  82700. (function (BABYLON) {
  82701. // We're mainly based on the logic defined into the FreeCamera code
  82702. /**
  82703. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82704. * being tilted forward or back and left or right.
  82705. */
  82706. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82707. __extends(DeviceOrientationCamera, _super);
  82708. /**
  82709. * Creates a new device orientation camera
  82710. * @param name The name of the camera
  82711. * @param position The start position camera
  82712. * @param scene The scene the camera belongs to
  82713. */
  82714. function DeviceOrientationCamera(name, position, scene) {
  82715. var _this = _super.call(this, name, position, scene) || this;
  82716. _this._quaternionCache = new BABYLON.Quaternion();
  82717. _this.inputs.addDeviceOrientation();
  82718. return _this;
  82719. }
  82720. /**
  82721. * Gets the current instance class name ("DeviceOrientationCamera").
  82722. * This helps avoiding instanceof at run time.
  82723. * @returns the class name
  82724. */
  82725. DeviceOrientationCamera.prototype.getClassName = function () {
  82726. return "DeviceOrientationCamera";
  82727. };
  82728. /**
  82729. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82730. */
  82731. DeviceOrientationCamera.prototype._checkInputs = function () {
  82732. _super.prototype._checkInputs.call(this);
  82733. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82734. if (this._initialQuaternion) {
  82735. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82736. }
  82737. };
  82738. /**
  82739. * Reset the camera to its default orientation on the specified axis only.
  82740. * @param axis The axis to reset
  82741. */
  82742. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82743. var _this = this;
  82744. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82745. //can only work if this camera has a rotation quaternion already.
  82746. if (!this.rotationQuaternion)
  82747. return;
  82748. if (!this._initialQuaternion) {
  82749. this._initialQuaternion = new BABYLON.Quaternion();
  82750. }
  82751. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82752. ['x', 'y', 'z'].forEach(function (axisName) {
  82753. if (!axis[axisName]) {
  82754. _this._initialQuaternion[axisName] = 0;
  82755. }
  82756. else {
  82757. _this._initialQuaternion[axisName] *= -1;
  82758. }
  82759. });
  82760. this._initialQuaternion.normalize();
  82761. //force rotation update
  82762. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82763. };
  82764. return DeviceOrientationCamera;
  82765. }(BABYLON.FreeCamera));
  82766. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82767. })(BABYLON || (BABYLON = {}));
  82768. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82769. "use strict";
  82770. var BABYLON;
  82771. (function (BABYLON) {
  82772. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82773. __extends(VRDeviceOrientationFreeCamera, _super);
  82774. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82775. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82776. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82777. var _this = _super.call(this, name, position, scene) || this;
  82778. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82779. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82780. return _this;
  82781. }
  82782. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82783. return "VRDeviceOrientationFreeCamera";
  82784. };
  82785. return VRDeviceOrientationFreeCamera;
  82786. }(BABYLON.DeviceOrientationCamera));
  82787. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82788. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82789. __extends(VRDeviceOrientationGamepadCamera, _super);
  82790. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82791. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82792. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82793. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82794. _this.inputs.addGamepad();
  82795. return _this;
  82796. }
  82797. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82798. return "VRDeviceOrientationGamepadCamera";
  82799. };
  82800. return VRDeviceOrientationGamepadCamera;
  82801. }(VRDeviceOrientationFreeCamera));
  82802. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82803. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82804. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82805. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82806. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82807. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82808. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82809. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82810. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82811. _this.inputs.addVRDeviceOrientation();
  82812. return _this;
  82813. }
  82814. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82815. return "VRDeviceOrientationArcRotateCamera";
  82816. };
  82817. return VRDeviceOrientationArcRotateCamera;
  82818. }(BABYLON.ArcRotateCamera));
  82819. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82820. })(BABYLON || (BABYLON = {}));
  82821. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82822. "use strict";
  82823. var BABYLON;
  82824. (function (BABYLON) {
  82825. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82826. __extends(AnaglyphFreeCamera, _super);
  82827. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82828. var _this = _super.call(this, name, position, scene) || this;
  82829. _this.interaxialDistance = interaxialDistance;
  82830. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82831. return _this;
  82832. }
  82833. AnaglyphFreeCamera.prototype.getClassName = function () {
  82834. return "AnaglyphFreeCamera";
  82835. };
  82836. return AnaglyphFreeCamera;
  82837. }(BABYLON.FreeCamera));
  82838. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82839. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82840. __extends(AnaglyphArcRotateCamera, _super);
  82841. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82842. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82843. _this.interaxialDistance = interaxialDistance;
  82844. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82845. return _this;
  82846. }
  82847. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82848. return "AnaglyphArcRotateCamera";
  82849. };
  82850. return AnaglyphArcRotateCamera;
  82851. }(BABYLON.ArcRotateCamera));
  82852. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82853. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82854. __extends(AnaglyphGamepadCamera, _super);
  82855. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82856. var _this = _super.call(this, name, position, scene) || this;
  82857. _this.interaxialDistance = interaxialDistance;
  82858. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82859. return _this;
  82860. }
  82861. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82862. return "AnaglyphGamepadCamera";
  82863. };
  82864. return AnaglyphGamepadCamera;
  82865. }(BABYLON.GamepadCamera));
  82866. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82867. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82868. __extends(AnaglyphUniversalCamera, _super);
  82869. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82870. var _this = _super.call(this, name, position, scene) || this;
  82871. _this.interaxialDistance = interaxialDistance;
  82872. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82873. return _this;
  82874. }
  82875. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82876. return "AnaglyphUniversalCamera";
  82877. };
  82878. return AnaglyphUniversalCamera;
  82879. }(BABYLON.UniversalCamera));
  82880. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82881. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82882. __extends(StereoscopicFreeCamera, _super);
  82883. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82884. var _this = _super.call(this, name, position, scene) || this;
  82885. _this.interaxialDistance = interaxialDistance;
  82886. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82887. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82888. return _this;
  82889. }
  82890. StereoscopicFreeCamera.prototype.getClassName = function () {
  82891. return "StereoscopicFreeCamera";
  82892. };
  82893. return StereoscopicFreeCamera;
  82894. }(BABYLON.FreeCamera));
  82895. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82896. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82897. __extends(StereoscopicArcRotateCamera, _super);
  82898. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82899. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82900. _this.interaxialDistance = interaxialDistance;
  82901. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82902. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82903. return _this;
  82904. }
  82905. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82906. return "StereoscopicArcRotateCamera";
  82907. };
  82908. return StereoscopicArcRotateCamera;
  82909. }(BABYLON.ArcRotateCamera));
  82910. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82911. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82912. __extends(StereoscopicGamepadCamera, _super);
  82913. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82914. var _this = _super.call(this, name, position, scene) || this;
  82915. _this.interaxialDistance = interaxialDistance;
  82916. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82917. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82918. return _this;
  82919. }
  82920. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82921. return "StereoscopicGamepadCamera";
  82922. };
  82923. return StereoscopicGamepadCamera;
  82924. }(BABYLON.GamepadCamera));
  82925. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82926. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82927. __extends(StereoscopicUniversalCamera, _super);
  82928. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82929. var _this = _super.call(this, name, position, scene) || this;
  82930. _this.interaxialDistance = interaxialDistance;
  82931. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82932. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82933. return _this;
  82934. }
  82935. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82936. return "StereoscopicUniversalCamera";
  82937. };
  82938. return StereoscopicUniversalCamera;
  82939. }(BABYLON.UniversalCamera));
  82940. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82941. })(BABYLON || (BABYLON = {}));
  82942. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82943. "use strict";
  82944. var BABYLON;
  82945. (function (BABYLON) {
  82946. var VRExperienceHelperGazer = /** @class */ (function () {
  82947. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82948. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82949. this.scene = scene;
  82950. this._pointerDownOnMeshAsked = false;
  82951. this._isActionableMesh = false;
  82952. this._teleportationRequestInitiated = false;
  82953. this._teleportationBackRequestInitiated = false;
  82954. this._dpadPressed = true;
  82955. this._activePointer = false;
  82956. this._id = VRExperienceHelperGazer._idCounter++;
  82957. // Gaze tracker
  82958. if (!gazeTrackerToClone) {
  82959. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82960. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82961. this._gazeTracker.isPickable = false;
  82962. this._gazeTracker.isVisible = false;
  82963. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82964. targetMat.specularColor = BABYLON.Color3.Black();
  82965. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82966. targetMat.backFaceCulling = false;
  82967. this._gazeTracker.material = targetMat;
  82968. }
  82969. else {
  82970. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82971. }
  82972. }
  82973. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82974. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82975. };
  82976. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82977. this._pointerDownOnMeshAsked = true;
  82978. if (this._currentMeshSelected && this._currentHit) {
  82979. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82980. }
  82981. };
  82982. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82983. if (this._currentMeshSelected && this._currentHit) {
  82984. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82985. }
  82986. this._pointerDownOnMeshAsked = false;
  82987. };
  82988. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82989. this._activePointer = true;
  82990. };
  82991. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82992. this._activePointer = false;
  82993. };
  82994. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82995. };
  82996. VRExperienceHelperGazer.prototype.dispose = function () {
  82997. this._interactionsEnabled = false;
  82998. this._teleportationEnabled = false;
  82999. };
  83000. VRExperienceHelperGazer._idCounter = 0;
  83001. return VRExperienceHelperGazer;
  83002. }());
  83003. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  83004. __extends(VRExperienceHelperControllerGazer, _super);
  83005. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  83006. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  83007. _this.webVRController = webVRController;
  83008. // Laser pointer
  83009. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  83010. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  83011. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  83012. laserPointerMaterial.alpha = 0.6;
  83013. _this._laserPointer.material = laserPointerMaterial;
  83014. _this._laserPointer.rotation.x = Math.PI / 2;
  83015. _this._laserPointer.position.z = -0.5;
  83016. _this._laserPointer.isVisible = false;
  83017. if (!webVRController.mesh) {
  83018. // Create an empty mesh that is used prior to loading the high quality model
  83019. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  83020. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  83021. preloadPointerPose.rotation.x = -0.7;
  83022. preloadMesh.addChild(preloadPointerPose);
  83023. webVRController.attachToMesh(preloadMesh);
  83024. }
  83025. _this._setLaserPointerParent(webVRController.mesh);
  83026. return _this;
  83027. }
  83028. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  83029. return this.webVRController.getForwardRay(length);
  83030. };
  83031. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  83032. _super.prototype._activatePointer.call(this);
  83033. this._laserPointer.isVisible = true;
  83034. };
  83035. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  83036. _super.prototype._deactivatePointer.call(this);
  83037. this._laserPointer.isVisible = false;
  83038. };
  83039. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  83040. this._laserPointer.material.emissiveColor = color;
  83041. };
  83042. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  83043. var makeNotPick = function (root) {
  83044. root.name += " laserPointer";
  83045. root.getChildMeshes().forEach(function (c) {
  83046. makeNotPick(c);
  83047. });
  83048. };
  83049. makeNotPick(mesh);
  83050. var childMeshes = mesh.getChildMeshes();
  83051. this.webVRController._pointingPoseNode = null;
  83052. for (var i = 0; i < childMeshes.length; i++) {
  83053. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  83054. mesh = childMeshes[i];
  83055. this.webVRController._pointingPoseNode = mesh;
  83056. break;
  83057. }
  83058. }
  83059. this._laserPointer.parent = mesh;
  83060. };
  83061. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  83062. this._laserPointer.scaling.y = distance;
  83063. this._laserPointer.position.z = -distance / 2;
  83064. };
  83065. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  83066. _super.prototype.dispose.call(this);
  83067. this._laserPointer.dispose();
  83068. };
  83069. return VRExperienceHelperControllerGazer;
  83070. }(VRExperienceHelperGazer));
  83071. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  83072. __extends(VRExperienceHelperCameraGazer, _super);
  83073. function VRExperienceHelperCameraGazer(getCamera, scene) {
  83074. var _this = _super.call(this, scene) || this;
  83075. _this.getCamera = getCamera;
  83076. return _this;
  83077. }
  83078. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  83079. var camera = this.getCamera();
  83080. if (camera) {
  83081. return camera.getForwardRay(length);
  83082. }
  83083. else {
  83084. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  83085. }
  83086. };
  83087. return VRExperienceHelperCameraGazer;
  83088. }(VRExperienceHelperGazer));
  83089. /**
  83090. * Helps to quickly add VR support to an existing scene.
  83091. * See http://doc.babylonjs.com/how_to/webvr_helper
  83092. */
  83093. var VRExperienceHelper = /** @class */ (function () {
  83094. /**
  83095. * Instantiates a VRExperienceHelper.
  83096. * Helps to quickly add VR support to an existing scene.
  83097. * @param scene The scene the VRExperienceHelper belongs to.
  83098. * @param webVROptions Options to modify the vr experience helper's behavior.
  83099. */
  83100. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  83101. if (webVROptions === void 0) { webVROptions = {}; }
  83102. var _this = this;
  83103. this.webVROptions = webVROptions;
  83104. // Can the system support WebVR, even if a headset isn't plugged in?
  83105. this._webVRsupported = false;
  83106. // If WebVR is supported, is a headset plugged in and are we ready to present?
  83107. this._webVRready = false;
  83108. // Are we waiting for the requestPresent callback to complete?
  83109. this._webVRrequesting = false;
  83110. // Are we presenting to the headset right now?
  83111. this._webVRpresenting = false;
  83112. // Are we presenting in the fullscreen fallback?
  83113. this._fullscreenVRpresenting = false;
  83114. /**
  83115. * Observable raised when entering VR.
  83116. */
  83117. this.onEnteringVRObservable = new BABYLON.Observable();
  83118. /**
  83119. * Observable raised when exiting VR.
  83120. */
  83121. this.onExitingVRObservable = new BABYLON.Observable();
  83122. /**
  83123. * Observable raised when controller mesh is loaded.
  83124. */
  83125. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  83126. this._useCustomVRButton = false;
  83127. this._teleportationRequested = false;
  83128. this._teleportActive = false;
  83129. this._floorMeshesCollection = [];
  83130. this._rotationAllowed = true;
  83131. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  83132. this._rotationRightAsked = false;
  83133. this._rotationLeftAsked = false;
  83134. this._isDefaultTeleportationTarget = true;
  83135. this._teleportationFillColor = "#444444";
  83136. this._teleportationBorderColor = "#FFFFFF";
  83137. this._rotationAngle = 0;
  83138. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  83139. this._padSensibilityUp = 0.65;
  83140. this._padSensibilityDown = 0.35;
  83141. this.leftController = null;
  83142. this.rightController = null;
  83143. /**
  83144. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  83145. */
  83146. this.onNewMeshSelected = new BABYLON.Observable();
  83147. /**
  83148. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  83149. */
  83150. this.onNewMeshPicked = new BABYLON.Observable();
  83151. /**
  83152. * Observable raised before camera teleportation
  83153. */
  83154. this.onBeforeCameraTeleport = new BABYLON.Observable();
  83155. /**
  83156. * Observable raised after camera teleportation
  83157. */
  83158. this.onAfterCameraTeleport = new BABYLON.Observable();
  83159. /**
  83160. * Observable raised when current selected mesh gets unselected
  83161. */
  83162. this.onSelectedMeshUnselected = new BABYLON.Observable();
  83163. /**
  83164. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  83165. */
  83166. this.teleportationEnabled = true;
  83167. this._teleportationInitialized = false;
  83168. this._interactionsEnabled = false;
  83169. this._interactionsRequested = false;
  83170. this._displayGaze = true;
  83171. this._displayLaserPointer = true;
  83172. this._onResize = function () {
  83173. _this.moveButtonToBottomRight();
  83174. if (_this._fullscreenVRpresenting && _this._webVRready) {
  83175. _this.exitVR();
  83176. }
  83177. };
  83178. this._onFullscreenChange = function () {
  83179. if (document.fullscreen !== undefined) {
  83180. _this._fullscreenVRpresenting = document.fullscreen;
  83181. }
  83182. else if (document.mozFullScreen !== undefined) {
  83183. _this._fullscreenVRpresenting = document.mozFullScreen;
  83184. }
  83185. else if (document.webkitIsFullScreen !== undefined) {
  83186. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  83187. }
  83188. else if (document.msIsFullScreen !== undefined) {
  83189. _this._fullscreenVRpresenting = document.msIsFullScreen;
  83190. }
  83191. if (!_this._fullscreenVRpresenting && _this._canvas) {
  83192. _this.exitVR();
  83193. if (!_this._useCustomVRButton) {
  83194. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  83195. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  83196. }
  83197. }
  83198. };
  83199. this.beforeRender = function () {
  83200. if (_this.leftController && _this.leftController._activePointer) {
  83201. _this._castRayAndSelectObject(_this.leftController);
  83202. }
  83203. if (_this.rightController && _this.rightController._activePointer) {
  83204. _this._castRayAndSelectObject(_this.rightController);
  83205. }
  83206. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  83207. _this._castRayAndSelectObject(_this._cameraGazer);
  83208. }
  83209. else {
  83210. _this._cameraGazer._gazeTracker.isVisible = false;
  83211. }
  83212. };
  83213. this._onNewGamepadConnected = function (gamepad) {
  83214. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  83215. if (gamepad.leftStick) {
  83216. gamepad.onleftstickchanged(function (stickValues) {
  83217. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  83218. // Listening to classic/xbox gamepad only if no VR controller is active
  83219. if ((!_this.leftController && !_this.rightController) ||
  83220. ((_this.leftController && !_this.leftController._activePointer) &&
  83221. (_this.rightController && !_this.rightController._activePointer))) {
  83222. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  83223. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  83224. }
  83225. }
  83226. });
  83227. }
  83228. if (gamepad.rightStick) {
  83229. gamepad.onrightstickchanged(function (stickValues) {
  83230. if (_this._teleportationInitialized) {
  83231. _this._checkRotate(stickValues, _this._cameraGazer);
  83232. }
  83233. });
  83234. }
  83235. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  83236. gamepad.onbuttondown(function (buttonPressed) {
  83237. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83238. _this._cameraGazer._selectionPointerDown();
  83239. }
  83240. });
  83241. gamepad.onbuttonup(function (buttonPressed) {
  83242. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83243. _this._cameraGazer._selectionPointerUp();
  83244. }
  83245. });
  83246. }
  83247. }
  83248. else {
  83249. var webVRController = gamepad;
  83250. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83251. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83252. _this.rightController = controller;
  83253. }
  83254. else {
  83255. _this.leftController = controller;
  83256. }
  83257. _this._tryEnableInteractionOnController(controller);
  83258. }
  83259. };
  83260. // 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
  83261. this._tryEnableInteractionOnController = function (controller) {
  83262. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83263. _this._enableInteractionOnController(controller);
  83264. }
  83265. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83266. _this._enableTeleportationOnController(controller);
  83267. }
  83268. };
  83269. this._onNewGamepadDisconnected = function (gamepad) {
  83270. if (gamepad instanceof BABYLON.WebVRController) {
  83271. if (gamepad.hand === "left" && _this.leftController != null) {
  83272. _this.leftController.dispose();
  83273. _this.leftController = null;
  83274. }
  83275. if (gamepad.hand === "right" && _this.rightController != null) {
  83276. _this.rightController.dispose();
  83277. _this.rightController = null;
  83278. }
  83279. }
  83280. };
  83281. this._workingVector = BABYLON.Vector3.Zero();
  83282. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83283. this._workingMatrix = BABYLON.Matrix.Identity();
  83284. this._scene = scene;
  83285. this._canvas = scene.getEngine().getRenderingCanvas();
  83286. // Parse options
  83287. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83288. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83289. }
  83290. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83291. webVROptions.createDeviceOrientationCamera = true;
  83292. }
  83293. if (webVROptions.defaultHeight === undefined) {
  83294. webVROptions.defaultHeight = 1.7;
  83295. }
  83296. if (webVROptions.useCustomVRButton) {
  83297. this._useCustomVRButton = true;
  83298. if (webVROptions.customVRButton) {
  83299. this._btnVR = webVROptions.customVRButton;
  83300. }
  83301. }
  83302. if (webVROptions.rayLength) {
  83303. this._rayLength = webVROptions.rayLength;
  83304. }
  83305. this._defaultHeight = webVROptions.defaultHeight;
  83306. if (webVROptions.positionScale) {
  83307. this._rayLength *= webVROptions.positionScale;
  83308. this._defaultHeight *= webVROptions.positionScale;
  83309. }
  83310. // Set position
  83311. if (this._scene.activeCamera) {
  83312. this._position = this._scene.activeCamera.position.clone();
  83313. }
  83314. else {
  83315. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83316. }
  83317. // Set non-vr camera
  83318. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83319. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83320. // Copy data from existing camera
  83321. if (this._scene.activeCamera) {
  83322. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83323. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83324. // Set rotation from previous camera
  83325. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83326. var targetCamera = this._scene.activeCamera;
  83327. if (targetCamera.rotationQuaternion) {
  83328. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83329. }
  83330. else {
  83331. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83332. }
  83333. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83334. }
  83335. }
  83336. this._scene.activeCamera = this._deviceOrientationCamera;
  83337. if (this._canvas) {
  83338. this._scene.activeCamera.attachControl(this._canvas);
  83339. }
  83340. }
  83341. else {
  83342. this._existingCamera = this._scene.activeCamera;
  83343. }
  83344. // Create VR cameras
  83345. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83346. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83347. }
  83348. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83349. this._webVRCamera.useStandingMatrix();
  83350. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83351. // Create default button
  83352. if (!this._useCustomVRButton) {
  83353. this._btnVR = document.createElement("BUTTON");
  83354. this._btnVR.className = "babylonVRicon";
  83355. this._btnVR.id = "babylonVRiconbtn";
  83356. this._btnVR.title = "Click to switch to VR";
  83357. 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) }";
  83358. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83359. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83360. // css += ".babylonVRicon.vrdisplaysupported { }";
  83361. // css += ".babylonVRicon.vrdisplayready { }";
  83362. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83363. var style = document.createElement('style');
  83364. style.appendChild(document.createTextNode(css));
  83365. document.getElementsByTagName('head')[0].appendChild(style);
  83366. this.moveButtonToBottomRight();
  83367. }
  83368. // VR button click event
  83369. if (this._btnVR) {
  83370. this._btnVR.addEventListener("click", function () {
  83371. if (!_this.isInVRMode) {
  83372. _this.enterVR();
  83373. }
  83374. else {
  83375. _this.exitVR();
  83376. }
  83377. });
  83378. }
  83379. // Window events
  83380. window.addEventListener("resize", this._onResize);
  83381. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83382. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83383. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83384. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83385. // Display vr button when headset is connected
  83386. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83387. this.displayVRButton();
  83388. }
  83389. else {
  83390. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83391. if (e.vrDisplay) {
  83392. _this.displayVRButton();
  83393. }
  83394. });
  83395. }
  83396. // Exiting VR mode using 'ESC' key on desktop
  83397. this._onKeyDown = function (event) {
  83398. if (event.keyCode === 27 && _this.isInVRMode) {
  83399. _this.exitVR();
  83400. }
  83401. };
  83402. document.addEventListener("keydown", this._onKeyDown);
  83403. // Exiting VR mode double tapping the touch screen
  83404. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83405. if (_this.isInVRMode) {
  83406. _this.exitVR();
  83407. if (_this._fullscreenVRpresenting) {
  83408. _this._scene.getEngine().switchFullscreen(true);
  83409. }
  83410. }
  83411. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83412. // Listen for WebVR display changes
  83413. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83414. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83415. this._onVRRequestPresentStart = function () {
  83416. _this._webVRrequesting = true;
  83417. _this.updateButtonVisibility();
  83418. };
  83419. this._onVRRequestPresentComplete = function (success) {
  83420. _this._webVRrequesting = false;
  83421. _this.updateButtonVisibility();
  83422. };
  83423. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83424. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83425. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83426. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83427. scene.onDisposeObservable.add(function () {
  83428. _this.dispose();
  83429. });
  83430. // Gamepad connection events
  83431. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83432. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83433. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83434. this.updateButtonVisibility();
  83435. //create easing functions
  83436. this._circleEase = new BABYLON.CircleEase();
  83437. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83438. }
  83439. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83440. /** Return this.onEnteringVRObservable
  83441. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83442. */
  83443. get: function () {
  83444. return this.onEnteringVRObservable;
  83445. },
  83446. enumerable: true,
  83447. configurable: true
  83448. });
  83449. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83450. /** Return this.onExitingVRObservable
  83451. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83452. */
  83453. get: function () {
  83454. return this.onExitingVRObservable;
  83455. },
  83456. enumerable: true,
  83457. configurable: true
  83458. });
  83459. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83460. /** Return this.onControllerMeshLoadedObservable
  83461. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83462. */
  83463. get: function () {
  83464. return this.onControllerMeshLoadedObservable;
  83465. },
  83466. enumerable: true,
  83467. configurable: true
  83468. });
  83469. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83470. /**
  83471. * The mesh used to display where the user is going to teleport.
  83472. */
  83473. get: function () {
  83474. return this._teleportationTarget;
  83475. },
  83476. /**
  83477. * Sets the mesh to be used to display where the user is going to teleport.
  83478. */
  83479. set: function (value) {
  83480. if (value) {
  83481. value.name = "teleportationTarget";
  83482. this._isDefaultTeleportationTarget = false;
  83483. this._teleportationTarget = value;
  83484. }
  83485. },
  83486. enumerable: true,
  83487. configurable: true
  83488. });
  83489. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83490. /**
  83491. * The mesh used to display where the user is selecting,
  83492. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83493. * See http://doc.babylonjs.com/resources/baking_transformations
  83494. */
  83495. get: function () {
  83496. return this._cameraGazer._gazeTracker;
  83497. },
  83498. set: function (value) {
  83499. if (value) {
  83500. this._cameraGazer._gazeTracker = value;
  83501. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83502. this._cameraGazer._gazeTracker.isPickable = false;
  83503. this._cameraGazer._gazeTracker.isVisible = false;
  83504. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83505. if (this.leftController) {
  83506. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83507. }
  83508. if (this.rightController) {
  83509. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83510. }
  83511. }
  83512. },
  83513. enumerable: true,
  83514. configurable: true
  83515. });
  83516. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83517. /**
  83518. * If the ray of the gaze should be displayed.
  83519. */
  83520. get: function () {
  83521. return this._displayGaze;
  83522. },
  83523. /**
  83524. * Sets if the ray of the gaze should be displayed.
  83525. */
  83526. set: function (value) {
  83527. this._displayGaze = value;
  83528. if (!value) {
  83529. this._cameraGazer._gazeTracker.isVisible = false;
  83530. if (this.leftController) {
  83531. this.leftController._gazeTracker.isVisible = false;
  83532. }
  83533. if (this.rightController) {
  83534. this.rightController._gazeTracker.isVisible = false;
  83535. }
  83536. }
  83537. },
  83538. enumerable: true,
  83539. configurable: true
  83540. });
  83541. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83542. /**
  83543. * If the ray of the LaserPointer should be displayed.
  83544. */
  83545. get: function () {
  83546. return this._displayLaserPointer;
  83547. },
  83548. /**
  83549. * Sets if the ray of the LaserPointer should be displayed.
  83550. */
  83551. set: function (value) {
  83552. this._displayLaserPointer = value;
  83553. if (!value) {
  83554. if (this.rightController) {
  83555. this.rightController._deactivatePointer();
  83556. this.rightController._gazeTracker.isVisible = false;
  83557. }
  83558. if (this.leftController) {
  83559. this.leftController._deactivatePointer();
  83560. this.leftController._gazeTracker.isVisible = false;
  83561. }
  83562. }
  83563. else {
  83564. if (this.rightController) {
  83565. this.rightController._activatePointer();
  83566. }
  83567. else if (this.leftController) {
  83568. this.leftController._activatePointer();
  83569. }
  83570. }
  83571. },
  83572. enumerable: true,
  83573. configurable: true
  83574. });
  83575. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83576. /**
  83577. * The deviceOrientationCamera used as the camera when not in VR.
  83578. */
  83579. get: function () {
  83580. return this._deviceOrientationCamera;
  83581. },
  83582. enumerable: true,
  83583. configurable: true
  83584. });
  83585. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83586. /**
  83587. * Based on the current WebVR support, returns the current VR camera used.
  83588. */
  83589. get: function () {
  83590. if (this._webVRready) {
  83591. return this._webVRCamera;
  83592. }
  83593. else {
  83594. return this._scene.activeCamera;
  83595. }
  83596. },
  83597. enumerable: true,
  83598. configurable: true
  83599. });
  83600. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83601. /**
  83602. * The webVRCamera which is used when in VR.
  83603. */
  83604. get: function () {
  83605. return this._webVRCamera;
  83606. },
  83607. enumerable: true,
  83608. configurable: true
  83609. });
  83610. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83611. /**
  83612. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83613. */
  83614. get: function () {
  83615. return this._vrDeviceOrientationCamera;
  83616. },
  83617. enumerable: true,
  83618. configurable: true
  83619. });
  83620. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83621. get: function () {
  83622. var result = this._cameraGazer._teleportationRequestInitiated
  83623. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83624. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83625. return result;
  83626. },
  83627. enumerable: true,
  83628. configurable: true
  83629. });
  83630. // Raised when one of the controller has loaded successfully its associated default mesh
  83631. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83632. if (this.leftController && this.leftController.webVRController == webVRController) {
  83633. if (webVRController.mesh) {
  83634. this.leftController._setLaserPointerParent(webVRController.mesh);
  83635. }
  83636. }
  83637. if (this.rightController && this.rightController.webVRController == webVRController) {
  83638. if (webVRController.mesh) {
  83639. this.rightController._setLaserPointerParent(webVRController.mesh);
  83640. }
  83641. }
  83642. try {
  83643. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83644. }
  83645. catch (err) {
  83646. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83647. }
  83648. };
  83649. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83650. /**
  83651. * Gets a value indicating if we are currently in VR mode.
  83652. */
  83653. get: function () {
  83654. return this._webVRpresenting || this._fullscreenVRpresenting;
  83655. },
  83656. enumerable: true,
  83657. configurable: true
  83658. });
  83659. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83660. var vrDisplay = this._scene.getEngine().getVRDevice();
  83661. if (vrDisplay) {
  83662. var wasPresenting = this._webVRpresenting;
  83663. // A VR display is connected
  83664. this._webVRpresenting = vrDisplay.isPresenting;
  83665. if (wasPresenting && !this._webVRpresenting)
  83666. this.exitVR();
  83667. }
  83668. else {
  83669. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83670. }
  83671. this.updateButtonVisibility();
  83672. };
  83673. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83674. this._webVRsupported = eventArgs.vrSupported;
  83675. this._webVRready = !!eventArgs.vrDisplay;
  83676. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83677. this.updateButtonVisibility();
  83678. };
  83679. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83680. if (this._canvas && !this._useCustomVRButton) {
  83681. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83682. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83683. }
  83684. };
  83685. VRExperienceHelper.prototype.displayVRButton = function () {
  83686. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83687. document.body.appendChild(this._btnVR);
  83688. this._btnVRDisplayed = true;
  83689. }
  83690. };
  83691. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83692. if (!this._btnVR || this._useCustomVRButton) {
  83693. return;
  83694. }
  83695. this._btnVR.className = "babylonVRicon";
  83696. if (this.isInVRMode) {
  83697. this._btnVR.className += " vrdisplaypresenting";
  83698. }
  83699. else {
  83700. if (this._webVRready)
  83701. this._btnVR.className += " vrdisplayready";
  83702. if (this._webVRsupported)
  83703. this._btnVR.className += " vrdisplaysupported";
  83704. if (this._webVRrequesting)
  83705. this._btnVR.className += " vrdisplayrequesting";
  83706. }
  83707. };
  83708. /**
  83709. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83710. * Otherwise, will use the fullscreen API.
  83711. */
  83712. VRExperienceHelper.prototype.enterVR = function () {
  83713. if (this.onEnteringVRObservable) {
  83714. try {
  83715. this.onEnteringVRObservable.notifyObservers(this);
  83716. }
  83717. catch (err) {
  83718. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83719. }
  83720. }
  83721. if (this._scene.activeCamera) {
  83722. this._position = this._scene.activeCamera.position.clone();
  83723. // make sure that we return to the last active camera
  83724. this._existingCamera = this._scene.activeCamera;
  83725. }
  83726. if (this._webVRrequesting)
  83727. return;
  83728. // If WebVR is supported and a headset is connected
  83729. if (this._webVRready) {
  83730. if (!this._webVRpresenting) {
  83731. this._webVRCamera.position = this._position;
  83732. this._scene.activeCamera = this._webVRCamera;
  83733. }
  83734. }
  83735. else if (this._vrDeviceOrientationCamera) {
  83736. this._vrDeviceOrientationCamera.position = this._position;
  83737. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83738. this._scene.getEngine().switchFullscreen(true);
  83739. this.updateButtonVisibility();
  83740. }
  83741. if (this._scene.activeCamera && this._canvas) {
  83742. this._scene.activeCamera.attachControl(this._canvas);
  83743. }
  83744. if (this._interactionsEnabled) {
  83745. this._scene.registerBeforeRender(this.beforeRender);
  83746. }
  83747. };
  83748. /**
  83749. * Attempt to exit VR, or fullscreen.
  83750. */
  83751. VRExperienceHelper.prototype.exitVR = function () {
  83752. if (this.onExitingVRObservable) {
  83753. try {
  83754. this.onExitingVRObservable.notifyObservers(this);
  83755. }
  83756. catch (err) {
  83757. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83758. }
  83759. }
  83760. if (this._webVRpresenting) {
  83761. this._scene.getEngine().disableVR();
  83762. }
  83763. if (this._scene.activeCamera) {
  83764. this._position = this._scene.activeCamera.position.clone();
  83765. }
  83766. if (this._deviceOrientationCamera) {
  83767. this._deviceOrientationCamera.position = this._position;
  83768. this._scene.activeCamera = this._deviceOrientationCamera;
  83769. if (this._canvas) {
  83770. this._scene.activeCamera.attachControl(this._canvas);
  83771. }
  83772. }
  83773. else if (this._existingCamera) {
  83774. this._existingCamera.position = this._position;
  83775. this._scene.activeCamera = this._existingCamera;
  83776. }
  83777. this.updateButtonVisibility();
  83778. if (this._interactionsEnabled) {
  83779. this._scene.unregisterBeforeRender(this.beforeRender);
  83780. }
  83781. };
  83782. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83783. /**
  83784. * The position of the vr experience helper.
  83785. */
  83786. get: function () {
  83787. return this._position;
  83788. },
  83789. /**
  83790. * Sets the position of the vr experience helper.
  83791. */
  83792. set: function (value) {
  83793. this._position = value;
  83794. if (this._scene.activeCamera) {
  83795. this._scene.activeCamera.position = value;
  83796. }
  83797. },
  83798. enumerable: true,
  83799. configurable: true
  83800. });
  83801. /**
  83802. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83803. */
  83804. VRExperienceHelper.prototype.enableInteractions = function () {
  83805. var _this = this;
  83806. if (!this._interactionsEnabled) {
  83807. this._interactionsRequested = true;
  83808. if (this.leftController) {
  83809. this._enableInteractionOnController(this.leftController);
  83810. }
  83811. if (this.rightController) {
  83812. this._enableInteractionOnController(this.rightController);
  83813. }
  83814. this.raySelectionPredicate = function (mesh) {
  83815. return mesh.isVisible;
  83816. };
  83817. this.meshSelectionPredicate = function (mesh) {
  83818. return true;
  83819. };
  83820. this._raySelectionPredicate = function (mesh) {
  83821. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83822. && mesh.name.indexOf("teleportationTarget") === -1
  83823. && mesh.name.indexOf("torusTeleportation") === -1
  83824. && mesh.name.indexOf("laserPointer") === -1)) {
  83825. return _this.raySelectionPredicate(mesh);
  83826. }
  83827. return false;
  83828. };
  83829. this._interactionsEnabled = true;
  83830. }
  83831. };
  83832. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83833. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83834. if (this._floorMeshesCollection[i].id === mesh.id) {
  83835. return true;
  83836. }
  83837. }
  83838. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83839. return true;
  83840. }
  83841. return false;
  83842. };
  83843. /**
  83844. * Adds a floor mesh to be used for teleportation.
  83845. * @param floorMesh the mesh to be used for teleportation.
  83846. */
  83847. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83848. if (!this._floorMeshesCollection) {
  83849. return;
  83850. }
  83851. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83852. return;
  83853. }
  83854. this._floorMeshesCollection.push(floorMesh);
  83855. };
  83856. /**
  83857. * Removes a floor mesh from being used for teleportation.
  83858. * @param floorMesh the mesh to be removed.
  83859. */
  83860. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83861. if (!this._floorMeshesCollection) {
  83862. return;
  83863. }
  83864. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83865. if (meshIndex !== -1) {
  83866. this._floorMeshesCollection.splice(meshIndex, 1);
  83867. }
  83868. };
  83869. /**
  83870. * Enables interactions and teleportation using the VR controllers and gaze.
  83871. * @param vrTeleportationOptions options to modify teleportation behavior.
  83872. */
  83873. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83874. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83875. if (!this._teleportationInitialized) {
  83876. this._teleportationRequested = true;
  83877. this.enableInteractions();
  83878. if (vrTeleportationOptions.floorMeshName) {
  83879. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83880. }
  83881. if (vrTeleportationOptions.floorMeshes) {
  83882. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83883. }
  83884. if (this.leftController != null) {
  83885. this._enableTeleportationOnController(this.leftController);
  83886. }
  83887. if (this.rightController != null) {
  83888. this._enableTeleportationOnController(this.rightController);
  83889. }
  83890. // Creates an image processing post process for the vignette not relying
  83891. // on the main scene configuration for image processing to reduce setup and spaces
  83892. // (gamma/linear) conflicts.
  83893. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83894. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83895. imageProcessingConfiguration.vignetteEnabled = true;
  83896. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83897. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83898. this._teleportationInitialized = true;
  83899. if (this._isDefaultTeleportationTarget) {
  83900. this._createTeleportationCircles();
  83901. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83902. }
  83903. }
  83904. };
  83905. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83906. var _this = this;
  83907. var controllerMesh = controller.webVRController.mesh;
  83908. if (controllerMesh) {
  83909. controller._interactionsEnabled = true;
  83910. controller._activatePointer();
  83911. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83912. // Enabling / disabling laserPointer
  83913. if (_this._displayLaserPointer && stateObject.value === 1) {
  83914. if (controller._activePointer) {
  83915. controller._deactivatePointer();
  83916. }
  83917. else {
  83918. controller._activatePointer();
  83919. }
  83920. if (_this.displayGaze) {
  83921. controller._gazeTracker.isVisible = controller._activePointer;
  83922. }
  83923. }
  83924. });
  83925. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83926. if (!controller._pointerDownOnMeshAsked) {
  83927. if (stateObject.value > _this._padSensibilityUp) {
  83928. controller._selectionPointerDown();
  83929. }
  83930. }
  83931. else if (stateObject.value < _this._padSensibilityDown) {
  83932. controller._selectionPointerUp();
  83933. }
  83934. });
  83935. }
  83936. };
  83937. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83938. // Dont teleport if another gaze already requested teleportation
  83939. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83940. return;
  83941. }
  83942. if (!gazer._teleportationRequestInitiated) {
  83943. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83944. gazer._activatePointer();
  83945. gazer._teleportationRequestInitiated = true;
  83946. }
  83947. }
  83948. else {
  83949. // Listening to the proper controller values changes to confirm teleportation
  83950. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83951. if (this._teleportActive) {
  83952. this._teleportCamera(this._haloCenter);
  83953. }
  83954. gazer._teleportationRequestInitiated = false;
  83955. }
  83956. }
  83957. };
  83958. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83959. // Only rotate when user is not currently selecting a teleportation location
  83960. if (gazer._teleportationRequestInitiated) {
  83961. return;
  83962. }
  83963. if (!this._rotationLeftAsked) {
  83964. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83965. this._rotationLeftAsked = true;
  83966. if (this._rotationAllowed) {
  83967. this._rotateCamera(false);
  83968. }
  83969. }
  83970. }
  83971. else {
  83972. if (stateObject.x > -this._padSensibilityDown) {
  83973. this._rotationLeftAsked = false;
  83974. }
  83975. }
  83976. if (!this._rotationRightAsked) {
  83977. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83978. this._rotationRightAsked = true;
  83979. if (this._rotationAllowed) {
  83980. this._rotateCamera(true);
  83981. }
  83982. }
  83983. }
  83984. else {
  83985. if (stateObject.x < this._padSensibilityDown) {
  83986. this._rotationRightAsked = false;
  83987. }
  83988. }
  83989. };
  83990. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83991. // Only teleport backwards when user is not currently selecting a teleportation location
  83992. if (gazer._teleportationRequestInitiated) {
  83993. return;
  83994. }
  83995. // Teleport backwards
  83996. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83997. if (!gazer._teleportationBackRequestInitiated) {
  83998. if (!this.currentVRCamera) {
  83999. return;
  84000. }
  84001. // Get rotation and position of the current camera
  84002. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  84003. var position = this.currentVRCamera.position;
  84004. // If the camera has device position, use that instead
  84005. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  84006. rotation = this.currentVRCamera.deviceRotationQuaternion;
  84007. position = this.currentVRCamera.devicePosition;
  84008. }
  84009. // Get matrix with only the y rotation of the device rotation
  84010. rotation.toEulerAnglesToRef(this._workingVector);
  84011. this._workingVector.z = 0;
  84012. this._workingVector.x = 0;
  84013. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  84014. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  84015. // Rotate backwards ray by device rotation to cast at the ground behind the user
  84016. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  84017. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  84018. var ray = new BABYLON.Ray(position, this._workingVector);
  84019. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  84020. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  84021. this._teleportCamera(hit.pickedPoint);
  84022. }
  84023. gazer._teleportationBackRequestInitiated = true;
  84024. }
  84025. }
  84026. else {
  84027. gazer._teleportationBackRequestInitiated = false;
  84028. }
  84029. };
  84030. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  84031. var _this = this;
  84032. var controllerMesh = controller.webVRController.mesh;
  84033. if (controllerMesh) {
  84034. if (!controller._interactionsEnabled) {
  84035. this._enableInteractionOnController(controller);
  84036. }
  84037. controller._interactionsEnabled = true;
  84038. controller._teleportationEnabled = true;
  84039. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  84040. controller._dpadPressed = false;
  84041. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  84042. controller._dpadPressed = stateObject.pressed;
  84043. if (!controller._dpadPressed) {
  84044. _this._rotationLeftAsked = false;
  84045. _this._rotationRightAsked = false;
  84046. controller._teleportationBackRequestInitiated = false;
  84047. }
  84048. });
  84049. }
  84050. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  84051. if (_this.teleportationEnabled) {
  84052. _this._checkTeleportBackwards(stateObject, controller);
  84053. _this._checkTeleportWithRay(stateObject, controller);
  84054. }
  84055. _this._checkRotate(stateObject, controller);
  84056. });
  84057. }
  84058. };
  84059. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  84060. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  84061. this._teleportationTarget.isPickable = false;
  84062. var length = 512;
  84063. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  84064. dynamicTexture.hasAlpha = true;
  84065. var context = dynamicTexture.getContext();
  84066. var centerX = length / 2;
  84067. var centerY = length / 2;
  84068. var radius = 200;
  84069. context.beginPath();
  84070. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  84071. context.fillStyle = this._teleportationFillColor;
  84072. context.fill();
  84073. context.lineWidth = 10;
  84074. context.strokeStyle = this._teleportationBorderColor;
  84075. context.stroke();
  84076. context.closePath();
  84077. dynamicTexture.update();
  84078. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  84079. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  84080. this._teleportationTarget.material = teleportationCircleMaterial;
  84081. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  84082. torus.isPickable = false;
  84083. torus.parent = this._teleportationTarget;
  84084. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  84085. var keys = [];
  84086. keys.push({
  84087. frame: 0,
  84088. value: 0
  84089. });
  84090. keys.push({
  84091. frame: 30,
  84092. value: 0.4
  84093. });
  84094. keys.push({
  84095. frame: 60,
  84096. value: 0
  84097. });
  84098. animationInnerCircle.setKeys(keys);
  84099. var easingFunction = new BABYLON.SineEase();
  84100. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  84101. animationInnerCircle.setEasingFunction(easingFunction);
  84102. torus.animations = [];
  84103. torus.animations.push(animationInnerCircle);
  84104. this._scene.beginAnimation(torus, 0, 60, true);
  84105. this._hideTeleportationTarget();
  84106. };
  84107. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  84108. this._teleportActive = true;
  84109. if (this._teleportationInitialized) {
  84110. this._teleportationTarget.isVisible = true;
  84111. if (this._isDefaultTeleportationTarget) {
  84112. this._teleportationTarget.getChildren()[0].isVisible = true;
  84113. }
  84114. }
  84115. };
  84116. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  84117. this._teleportActive = false;
  84118. if (this._teleportationInitialized) {
  84119. this._teleportationTarget.isVisible = false;
  84120. if (this._isDefaultTeleportationTarget) {
  84121. this._teleportationTarget.getChildren()[0].isVisible = false;
  84122. }
  84123. }
  84124. };
  84125. VRExperienceHelper.prototype._rotateCamera = function (right) {
  84126. var _this = this;
  84127. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84128. return;
  84129. }
  84130. if (right) {
  84131. this._rotationAngle++;
  84132. }
  84133. else {
  84134. this._rotationAngle--;
  84135. }
  84136. this.currentVRCamera.animations = [];
  84137. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  84138. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84139. var animationRotationKeys = [];
  84140. animationRotationKeys.push({
  84141. frame: 0,
  84142. value: this.currentVRCamera.rotationQuaternion
  84143. });
  84144. animationRotationKeys.push({
  84145. frame: 6,
  84146. value: target
  84147. });
  84148. animationRotation.setKeys(animationRotationKeys);
  84149. animationRotation.setEasingFunction(this._circleEase);
  84150. this.currentVRCamera.animations.push(animationRotation);
  84151. this._postProcessMove.animations = [];
  84152. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84153. var vignetteWeightKeys = [];
  84154. vignetteWeightKeys.push({
  84155. frame: 0,
  84156. value: 0
  84157. });
  84158. vignetteWeightKeys.push({
  84159. frame: 3,
  84160. value: 4
  84161. });
  84162. vignetteWeightKeys.push({
  84163. frame: 6,
  84164. value: 0
  84165. });
  84166. animationPP.setKeys(vignetteWeightKeys);
  84167. animationPP.setEasingFunction(this._circleEase);
  84168. this._postProcessMove.animations.push(animationPP);
  84169. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84170. var vignetteStretchKeys = [];
  84171. vignetteStretchKeys.push({
  84172. frame: 0,
  84173. value: 0
  84174. });
  84175. vignetteStretchKeys.push({
  84176. frame: 3,
  84177. value: 10
  84178. });
  84179. vignetteStretchKeys.push({
  84180. frame: 6,
  84181. value: 0
  84182. });
  84183. animationPP2.setKeys(vignetteStretchKeys);
  84184. animationPP2.setEasingFunction(this._circleEase);
  84185. this._postProcessMove.animations.push(animationPP2);
  84186. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84187. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84188. this._postProcessMove.samples = 4;
  84189. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84190. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  84191. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84192. });
  84193. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  84194. };
  84195. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  84196. if (hit.pickedPoint) {
  84197. if (gazer._teleportationRequestInitiated) {
  84198. this._displayTeleportationTarget();
  84199. this._haloCenter.copyFrom(hit.pickedPoint);
  84200. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  84201. }
  84202. var pickNormal = hit.getNormal(true, false);
  84203. if (pickNormal) {
  84204. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84205. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84206. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  84207. }
  84208. this._teleportationTarget.position.y += 0.1;
  84209. }
  84210. };
  84211. VRExperienceHelper.prototype._teleportCamera = function (location) {
  84212. var _this = this;
  84213. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84214. return;
  84215. }
  84216. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  84217. // offset of the headset from the anchor.
  84218. if (this.webVRCamera.leftCamera) {
  84219. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  84220. this._workingVector.subtractInPlace(this.webVRCamera.position);
  84221. location.subtractToRef(this._workingVector, this._workingVector);
  84222. }
  84223. else {
  84224. this._workingVector.copyFrom(location);
  84225. }
  84226. // Add height to account for user's height offset
  84227. if (this.isInVRMode) {
  84228. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  84229. }
  84230. else {
  84231. this._workingVector.y += this._defaultHeight;
  84232. }
  84233. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  84234. // Create animation from the camera's position to the new location
  84235. this.currentVRCamera.animations = [];
  84236. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84237. var animationCameraTeleportationKeys = [{
  84238. frame: 0,
  84239. value: this.currentVRCamera.position
  84240. },
  84241. {
  84242. frame: 11,
  84243. value: this._workingVector
  84244. }
  84245. ];
  84246. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  84247. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84248. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84249. this._postProcessMove.animations = [];
  84250. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84251. var vignetteWeightKeys = [];
  84252. vignetteWeightKeys.push({
  84253. frame: 0,
  84254. value: 0
  84255. });
  84256. vignetteWeightKeys.push({
  84257. frame: 5,
  84258. value: 8
  84259. });
  84260. vignetteWeightKeys.push({
  84261. frame: 11,
  84262. value: 0
  84263. });
  84264. animationPP.setKeys(vignetteWeightKeys);
  84265. this._postProcessMove.animations.push(animationPP);
  84266. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84267. var vignetteStretchKeys = [];
  84268. vignetteStretchKeys.push({
  84269. frame: 0,
  84270. value: 0
  84271. });
  84272. vignetteStretchKeys.push({
  84273. frame: 5,
  84274. value: 10
  84275. });
  84276. vignetteStretchKeys.push({
  84277. frame: 11,
  84278. value: 0
  84279. });
  84280. animationPP2.setKeys(vignetteStretchKeys);
  84281. this._postProcessMove.animations.push(animationPP2);
  84282. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84283. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84284. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84285. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84286. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84287. });
  84288. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84289. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84290. });
  84291. this._hideTeleportationTarget();
  84292. };
  84293. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84294. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84295. return;
  84296. }
  84297. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84298. // Moving the gazeTracker on the mesh face targetted
  84299. if (hit && hit.pickedPoint) {
  84300. if (this._displayGaze) {
  84301. var multiplier = 1;
  84302. gazer._gazeTracker.isVisible = true;
  84303. if (gazer._isActionableMesh) {
  84304. multiplier = 3;
  84305. }
  84306. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84307. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84308. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84309. var pickNormal = hit.getNormal();
  84310. // To avoid z-fighting
  84311. var deltaFighting = 0.002;
  84312. if (pickNormal) {
  84313. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84314. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84315. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84316. }
  84317. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84318. if (gazer._gazeTracker.position.x < 0) {
  84319. gazer._gazeTracker.position.x += deltaFighting;
  84320. }
  84321. else {
  84322. gazer._gazeTracker.position.x -= deltaFighting;
  84323. }
  84324. if (gazer._gazeTracker.position.y < 0) {
  84325. gazer._gazeTracker.position.y += deltaFighting;
  84326. }
  84327. else {
  84328. gazer._gazeTracker.position.y -= deltaFighting;
  84329. }
  84330. if (gazer._gazeTracker.position.z < 0) {
  84331. gazer._gazeTracker.position.z += deltaFighting;
  84332. }
  84333. else {
  84334. gazer._gazeTracker.position.z -= deltaFighting;
  84335. }
  84336. }
  84337. // Changing the size of the laser pointer based on the distance from the targetted point
  84338. gazer._updatePointerDistance(hit.distance);
  84339. }
  84340. else {
  84341. gazer._gazeTracker.isVisible = false;
  84342. }
  84343. if (hit && hit.pickedMesh) {
  84344. gazer._currentHit = hit;
  84345. if (gazer._pointerDownOnMeshAsked) {
  84346. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84347. }
  84348. // The object selected is the floor, we're in a teleportation scenario
  84349. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84350. // Moving the teleportation area to this targetted point
  84351. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84352. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84353. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84354. }
  84355. gazer._currentMeshSelected = null;
  84356. if (gazer._teleportationRequestInitiated) {
  84357. this._moveTeleportationSelectorTo(hit, gazer);
  84358. }
  84359. return;
  84360. }
  84361. // If not, we're in a selection scenario
  84362. //this._teleportationAllowed = false;
  84363. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84364. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84365. this.onNewMeshPicked.notifyObservers(hit);
  84366. gazer._currentMeshSelected = hit.pickedMesh;
  84367. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84368. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84369. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84370. gazer._isActionableMesh = true;
  84371. }
  84372. else {
  84373. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84374. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84375. gazer._isActionableMesh = false;
  84376. }
  84377. try {
  84378. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84379. }
  84380. catch (err) {
  84381. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84382. }
  84383. }
  84384. else {
  84385. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84386. gazer._currentMeshSelected = null;
  84387. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84388. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84389. }
  84390. }
  84391. }
  84392. else {
  84393. gazer._currentHit = null;
  84394. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84395. gazer._currentMeshSelected = null;
  84396. //this._teleportationAllowed = false;
  84397. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84398. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84399. }
  84400. };
  84401. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84402. if (mesh) {
  84403. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84404. }
  84405. };
  84406. /**
  84407. * Sets the color of the laser ray from the vr controllers.
  84408. * @param color new color for the ray.
  84409. */
  84410. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84411. if (this.leftController) {
  84412. this.leftController._setLaserPointerColor(color);
  84413. }
  84414. if (this.rightController) {
  84415. this.rightController._setLaserPointerColor(color);
  84416. }
  84417. };
  84418. /**
  84419. * Sets the color of the ray from the vr headsets gaze.
  84420. * @param color new color for the ray.
  84421. */
  84422. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84423. if (!this._cameraGazer._gazeTracker.material) {
  84424. return;
  84425. }
  84426. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84427. if (this.leftController) {
  84428. this.leftController._gazeTracker.material.emissiveColor = color;
  84429. }
  84430. if (this.rightController) {
  84431. this.rightController._gazeTracker.material.emissiveColor = color;
  84432. }
  84433. };
  84434. /**
  84435. * Exits VR and disposes of the vr experience helper
  84436. */
  84437. VRExperienceHelper.prototype.dispose = function () {
  84438. if (this.isInVRMode) {
  84439. this.exitVR();
  84440. }
  84441. if (this._postProcessMove) {
  84442. this._postProcessMove.dispose();
  84443. }
  84444. if (this._webVRCamera) {
  84445. this._webVRCamera.dispose();
  84446. }
  84447. if (this._vrDeviceOrientationCamera) {
  84448. this._vrDeviceOrientationCamera.dispose();
  84449. }
  84450. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84451. document.body.removeChild(this._btnVR);
  84452. }
  84453. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84454. this._deviceOrientationCamera.dispose();
  84455. }
  84456. if (this._cameraGazer) {
  84457. this._cameraGazer.dispose();
  84458. }
  84459. if (this.leftController) {
  84460. this.leftController.dispose();
  84461. }
  84462. if (this.rightController) {
  84463. this.rightController.dispose();
  84464. }
  84465. if (this._teleportationTarget) {
  84466. this._teleportationTarget.dispose();
  84467. }
  84468. this._floorMeshesCollection = [];
  84469. document.removeEventListener("keydown", this._onKeyDown);
  84470. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84471. window.removeEventListener("resize", this._onResize);
  84472. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84473. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84474. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84475. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84476. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84477. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84478. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84479. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84480. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84481. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84482. this._scene.unregisterBeforeRender(this.beforeRender);
  84483. };
  84484. /**
  84485. * Gets the name of the VRExperienceHelper class
  84486. * @returns "VRExperienceHelper"
  84487. */
  84488. VRExperienceHelper.prototype.getClassName = function () {
  84489. return "VRExperienceHelper";
  84490. };
  84491. return VRExperienceHelper;
  84492. }());
  84493. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84494. })(BABYLON || (BABYLON = {}));
  84495. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84496. "use strict";
  84497. // Mainly based on these 2 articles :
  84498. // 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
  84499. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84500. var BABYLON;
  84501. (function (BABYLON) {
  84502. var JoystickAxis;
  84503. (function (JoystickAxis) {
  84504. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84505. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84506. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84507. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84508. var VirtualJoystick = /** @class */ (function () {
  84509. function VirtualJoystick(leftJoystick) {
  84510. var _this = this;
  84511. if (leftJoystick) {
  84512. this._leftJoystick = true;
  84513. }
  84514. else {
  84515. this._leftJoystick = false;
  84516. }
  84517. VirtualJoystick._globalJoystickIndex++;
  84518. // By default left & right arrow keys are moving the X
  84519. // and up & down keys are moving the Y
  84520. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84521. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84522. this.reverseLeftRight = false;
  84523. this.reverseUpDown = false;
  84524. // collections of pointers
  84525. this._touches = new BABYLON.StringDictionary();
  84526. this.deltaPosition = BABYLON.Vector3.Zero();
  84527. this._joystickSensibility = 25;
  84528. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84529. this._onResize = function (evt) {
  84530. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84531. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84532. if (VirtualJoystick.vjCanvas) {
  84533. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84534. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84535. }
  84536. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84537. };
  84538. // injecting a canvas element on top of the canvas 3D game
  84539. if (!VirtualJoystick.vjCanvas) {
  84540. window.addEventListener("resize", this._onResize, false);
  84541. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84542. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84543. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84544. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84545. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84546. VirtualJoystick.vjCanvas.style.width = "100%";
  84547. VirtualJoystick.vjCanvas.style.height = "100%";
  84548. VirtualJoystick.vjCanvas.style.position = "absolute";
  84549. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84550. VirtualJoystick.vjCanvas.style.top = "0px";
  84551. VirtualJoystick.vjCanvas.style.left = "0px";
  84552. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84553. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84554. // Support for jQuery PEP polyfill
  84555. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84556. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84557. if (!context) {
  84558. throw new Error("Unable to create canvas for virtual joystick");
  84559. }
  84560. VirtualJoystick.vjCanvasContext = context;
  84561. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84562. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84563. document.body.appendChild(VirtualJoystick.vjCanvas);
  84564. }
  84565. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84566. this.pressed = false;
  84567. // default joystick color
  84568. this._joystickColor = "cyan";
  84569. this._joystickPointerID = -1;
  84570. // current joystick position
  84571. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84572. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84573. // origin joystick position
  84574. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84575. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84576. this._onPointerDownHandlerRef = function (evt) {
  84577. _this._onPointerDown(evt);
  84578. };
  84579. this._onPointerMoveHandlerRef = function (evt) {
  84580. _this._onPointerMove(evt);
  84581. };
  84582. this._onPointerUpHandlerRef = function (evt) {
  84583. _this._onPointerUp(evt);
  84584. };
  84585. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84586. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84587. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84588. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84589. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84590. evt.preventDefault(); // Disables system menu
  84591. }, false);
  84592. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84593. }
  84594. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84595. this._joystickSensibility = newJoystickSensibility;
  84596. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84597. };
  84598. VirtualJoystick.prototype._onPointerDown = function (e) {
  84599. var positionOnScreenCondition;
  84600. e.preventDefault();
  84601. if (this._leftJoystick === true) {
  84602. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84603. }
  84604. else {
  84605. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84606. }
  84607. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84608. // First contact will be dedicated to the virtual joystick
  84609. this._joystickPointerID = e.pointerId;
  84610. this._joystickPointerStartPos.x = e.clientX;
  84611. this._joystickPointerStartPos.y = e.clientY;
  84612. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84613. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84614. this._deltaJoystickVector.x = 0;
  84615. this._deltaJoystickVector.y = 0;
  84616. this.pressed = true;
  84617. this._touches.add(e.pointerId.toString(), e);
  84618. }
  84619. else {
  84620. // You can only trigger the action buttons with a joystick declared
  84621. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84622. this._action();
  84623. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84624. }
  84625. }
  84626. };
  84627. VirtualJoystick.prototype._onPointerMove = function (e) {
  84628. // If the current pointer is the one associated to the joystick (first touch contact)
  84629. if (this._joystickPointerID == e.pointerId) {
  84630. this._joystickPointerPos.x = e.clientX;
  84631. this._joystickPointerPos.y = e.clientY;
  84632. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84633. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84634. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84635. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84636. switch (this._axisTargetedByLeftAndRight) {
  84637. case JoystickAxis.X:
  84638. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84639. break;
  84640. case JoystickAxis.Y:
  84641. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84642. break;
  84643. case JoystickAxis.Z:
  84644. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84645. break;
  84646. }
  84647. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84648. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84649. switch (this._axisTargetedByUpAndDown) {
  84650. case JoystickAxis.X:
  84651. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84652. break;
  84653. case JoystickAxis.Y:
  84654. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84655. break;
  84656. case JoystickAxis.Z:
  84657. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84658. break;
  84659. }
  84660. }
  84661. else {
  84662. var data = this._touches.get(e.pointerId.toString());
  84663. if (data) {
  84664. data.x = e.clientX;
  84665. data.y = e.clientY;
  84666. }
  84667. }
  84668. };
  84669. VirtualJoystick.prototype._onPointerUp = function (e) {
  84670. if (this._joystickPointerID == e.pointerId) {
  84671. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84672. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84673. this._joystickPointerID = -1;
  84674. this.pressed = false;
  84675. }
  84676. else {
  84677. var touch = this._touches.get(e.pointerId.toString());
  84678. if (touch) {
  84679. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84680. }
  84681. }
  84682. this._deltaJoystickVector.x = 0;
  84683. this._deltaJoystickVector.y = 0;
  84684. this._touches.remove(e.pointerId.toString());
  84685. };
  84686. /**
  84687. * Change the color of the virtual joystick
  84688. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84689. */
  84690. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84691. this._joystickColor = newColor;
  84692. };
  84693. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84694. this._action = action;
  84695. };
  84696. // Define which axis you'd like to control for left & right
  84697. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84698. switch (axis) {
  84699. case JoystickAxis.X:
  84700. case JoystickAxis.Y:
  84701. case JoystickAxis.Z:
  84702. this._axisTargetedByLeftAndRight = axis;
  84703. break;
  84704. default:
  84705. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84706. break;
  84707. }
  84708. };
  84709. // Define which axis you'd like to control for up & down
  84710. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84711. switch (axis) {
  84712. case JoystickAxis.X:
  84713. case JoystickAxis.Y:
  84714. case JoystickAxis.Z:
  84715. this._axisTargetedByUpAndDown = axis;
  84716. break;
  84717. default:
  84718. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84719. break;
  84720. }
  84721. };
  84722. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84723. var _this = this;
  84724. if (this.pressed) {
  84725. this._touches.forEach(function (key, touch) {
  84726. if (touch.pointerId === _this._joystickPointerID) {
  84727. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84728. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84729. VirtualJoystick.vjCanvasContext.beginPath();
  84730. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84731. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84732. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84733. VirtualJoystick.vjCanvasContext.stroke();
  84734. VirtualJoystick.vjCanvasContext.closePath();
  84735. VirtualJoystick.vjCanvasContext.beginPath();
  84736. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84737. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84738. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84739. VirtualJoystick.vjCanvasContext.stroke();
  84740. VirtualJoystick.vjCanvasContext.closePath();
  84741. VirtualJoystick.vjCanvasContext.beginPath();
  84742. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84743. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84744. VirtualJoystick.vjCanvasContext.stroke();
  84745. VirtualJoystick.vjCanvasContext.closePath();
  84746. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84747. }
  84748. else {
  84749. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84750. VirtualJoystick.vjCanvasContext.beginPath();
  84751. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84752. VirtualJoystick.vjCanvasContext.beginPath();
  84753. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84754. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84755. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84756. VirtualJoystick.vjCanvasContext.stroke();
  84757. VirtualJoystick.vjCanvasContext.closePath();
  84758. touch.prevX = touch.x;
  84759. touch.prevY = touch.y;
  84760. }
  84761. ;
  84762. });
  84763. }
  84764. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84765. };
  84766. VirtualJoystick.prototype.releaseCanvas = function () {
  84767. if (VirtualJoystick.vjCanvas) {
  84768. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84769. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84770. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84771. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84772. window.removeEventListener("resize", this._onResize);
  84773. document.body.removeChild(VirtualJoystick.vjCanvas);
  84774. VirtualJoystick.vjCanvas = null;
  84775. }
  84776. };
  84777. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84778. VirtualJoystick._globalJoystickIndex = 0;
  84779. return VirtualJoystick;
  84780. }());
  84781. BABYLON.VirtualJoystick = VirtualJoystick;
  84782. })(BABYLON || (BABYLON = {}));
  84783. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84784. "use strict";
  84785. var BABYLON;
  84786. (function (BABYLON) {
  84787. // We're mainly based on the logic defined into the FreeCamera code
  84788. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84789. __extends(VirtualJoysticksCamera, _super);
  84790. function VirtualJoysticksCamera(name, position, scene) {
  84791. var _this = _super.call(this, name, position, scene) || this;
  84792. _this.inputs.addVirtualJoystick();
  84793. return _this;
  84794. }
  84795. VirtualJoysticksCamera.prototype.getClassName = function () {
  84796. return "VirtualJoysticksCamera";
  84797. };
  84798. return VirtualJoysticksCamera;
  84799. }(BABYLON.FreeCamera));
  84800. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84801. })(BABYLON || (BABYLON = {}));
  84802. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84803. "use strict";
  84804. var BABYLON;
  84805. (function (BABYLON) {
  84806. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84807. function FreeCameraVirtualJoystickInput() {
  84808. }
  84809. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84810. return this._leftjoystick;
  84811. };
  84812. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84813. return this._rightjoystick;
  84814. };
  84815. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84816. if (this._leftjoystick) {
  84817. var camera = this.camera;
  84818. var speed = camera._computeLocalCameraSpeed() * 50;
  84819. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84820. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84821. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84822. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84823. if (!this._leftjoystick.pressed) {
  84824. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84825. }
  84826. if (!this._rightjoystick.pressed) {
  84827. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84828. }
  84829. }
  84830. };
  84831. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84832. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84833. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84834. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84835. this._leftjoystick.setJoystickSensibility(0.15);
  84836. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84837. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84838. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84839. this._rightjoystick.reverseUpDown = true;
  84840. this._rightjoystick.setJoystickSensibility(0.05);
  84841. this._rightjoystick.setJoystickColor("yellow");
  84842. };
  84843. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84844. this._leftjoystick.releaseCanvas();
  84845. this._rightjoystick.releaseCanvas();
  84846. };
  84847. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84848. return "FreeCameraVirtualJoystickInput";
  84849. };
  84850. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84851. return "virtualJoystick";
  84852. };
  84853. return FreeCameraVirtualJoystickInput;
  84854. }());
  84855. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84856. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84857. })(BABYLON || (BABYLON = {}));
  84858. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84859. "use strict";
  84860. var BABYLON;
  84861. (function (BABYLON) {
  84862. var SimplificationSettings = /** @class */ (function () {
  84863. function SimplificationSettings(quality, distance, optimizeMesh) {
  84864. this.quality = quality;
  84865. this.distance = distance;
  84866. this.optimizeMesh = optimizeMesh;
  84867. }
  84868. return SimplificationSettings;
  84869. }());
  84870. BABYLON.SimplificationSettings = SimplificationSettings;
  84871. var SimplificationQueue = /** @class */ (function () {
  84872. function SimplificationQueue() {
  84873. this.running = false;
  84874. this._simplificationArray = [];
  84875. }
  84876. SimplificationQueue.prototype.addTask = function (task) {
  84877. this._simplificationArray.push(task);
  84878. };
  84879. SimplificationQueue.prototype.executeNext = function () {
  84880. var task = this._simplificationArray.pop();
  84881. if (task) {
  84882. this.running = true;
  84883. this.runSimplification(task);
  84884. }
  84885. else {
  84886. this.running = false;
  84887. }
  84888. };
  84889. SimplificationQueue.prototype.runSimplification = function (task) {
  84890. var _this = this;
  84891. if (task.parallelProcessing) {
  84892. //parallel simplifier
  84893. task.settings.forEach(function (setting) {
  84894. var simplifier = _this.getSimplifier(task);
  84895. simplifier.simplify(setting, function (newMesh) {
  84896. task.mesh.addLODLevel(setting.distance, newMesh);
  84897. newMesh.isVisible = true;
  84898. //check if it is the last
  84899. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84900. //all done, run the success callback.
  84901. task.successCallback();
  84902. }
  84903. _this.executeNext();
  84904. });
  84905. });
  84906. }
  84907. else {
  84908. //single simplifier.
  84909. var simplifier = this.getSimplifier(task);
  84910. var runDecimation = function (setting, callback) {
  84911. simplifier.simplify(setting, function (newMesh) {
  84912. task.mesh.addLODLevel(setting.distance, newMesh);
  84913. newMesh.isVisible = true;
  84914. //run the next quality level
  84915. callback();
  84916. });
  84917. };
  84918. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84919. runDecimation(task.settings[loop.index], function () {
  84920. loop.executeNext();
  84921. });
  84922. }, function () {
  84923. //execution ended, run the success callback.
  84924. if (task.successCallback) {
  84925. task.successCallback();
  84926. }
  84927. _this.executeNext();
  84928. });
  84929. }
  84930. };
  84931. SimplificationQueue.prototype.getSimplifier = function (task) {
  84932. switch (task.simplificationType) {
  84933. case SimplificationType.QUADRATIC:
  84934. default:
  84935. return new QuadraticErrorSimplification(task.mesh);
  84936. }
  84937. };
  84938. return SimplificationQueue;
  84939. }());
  84940. BABYLON.SimplificationQueue = SimplificationQueue;
  84941. /**
  84942. * The implemented types of simplification.
  84943. * At the moment only Quadratic Error Decimation is implemented.
  84944. */
  84945. var SimplificationType;
  84946. (function (SimplificationType) {
  84947. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84948. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84949. var DecimationTriangle = /** @class */ (function () {
  84950. function DecimationTriangle(vertices) {
  84951. this.vertices = vertices;
  84952. this.error = new Array(4);
  84953. this.deleted = false;
  84954. this.isDirty = false;
  84955. this.deletePending = false;
  84956. this.borderFactor = 0;
  84957. }
  84958. return DecimationTriangle;
  84959. }());
  84960. BABYLON.DecimationTriangle = DecimationTriangle;
  84961. var DecimationVertex = /** @class */ (function () {
  84962. function DecimationVertex(position, id) {
  84963. this.position = position;
  84964. this.id = id;
  84965. this.isBorder = true;
  84966. this.q = new QuadraticMatrix();
  84967. this.triangleCount = 0;
  84968. this.triangleStart = 0;
  84969. this.originalOffsets = [];
  84970. }
  84971. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84972. this.position.copyFrom(newPosition);
  84973. };
  84974. return DecimationVertex;
  84975. }());
  84976. BABYLON.DecimationVertex = DecimationVertex;
  84977. var QuadraticMatrix = /** @class */ (function () {
  84978. function QuadraticMatrix(data) {
  84979. this.data = new Array(10);
  84980. for (var i = 0; i < 10; ++i) {
  84981. if (data && data[i]) {
  84982. this.data[i] = data[i];
  84983. }
  84984. else {
  84985. this.data[i] = 0;
  84986. }
  84987. }
  84988. }
  84989. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84990. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84991. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84992. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84993. return det;
  84994. };
  84995. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84996. for (var i = 0; i < 10; ++i) {
  84997. this.data[i] += matrix.data[i];
  84998. }
  84999. };
  85000. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  85001. for (var i = 0; i < 10; ++i) {
  85002. this.data[i] += data[i];
  85003. }
  85004. };
  85005. QuadraticMatrix.prototype.add = function (matrix) {
  85006. var m = new QuadraticMatrix();
  85007. for (var i = 0; i < 10; ++i) {
  85008. m.data[i] = this.data[i] + matrix.data[i];
  85009. }
  85010. return m;
  85011. };
  85012. QuadraticMatrix.FromData = function (a, b, c, d) {
  85013. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  85014. };
  85015. //returning an array to avoid garbage collection
  85016. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  85017. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  85018. };
  85019. return QuadraticMatrix;
  85020. }());
  85021. BABYLON.QuadraticMatrix = QuadraticMatrix;
  85022. var Reference = /** @class */ (function () {
  85023. function Reference(vertexId, triangleId) {
  85024. this.vertexId = vertexId;
  85025. this.triangleId = triangleId;
  85026. }
  85027. return Reference;
  85028. }());
  85029. BABYLON.Reference = Reference;
  85030. /**
  85031. * An implementation of the Quadratic Error simplification algorithm.
  85032. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  85033. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  85034. * @author RaananW
  85035. */
  85036. var QuadraticErrorSimplification = /** @class */ (function () {
  85037. function QuadraticErrorSimplification(_mesh) {
  85038. this._mesh = _mesh;
  85039. this.syncIterations = 5000;
  85040. this.aggressiveness = 7;
  85041. this.decimationIterations = 100;
  85042. this.boundingBoxEpsilon = BABYLON.Epsilon;
  85043. }
  85044. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  85045. var _this = this;
  85046. this.initDecimatedMesh();
  85047. //iterating through the submeshes array, one after the other.
  85048. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  85049. _this.initWithMesh(loop.index, function () {
  85050. _this.runDecimation(settings, loop.index, function () {
  85051. loop.executeNext();
  85052. });
  85053. }, settings.optimizeMesh);
  85054. }, function () {
  85055. setTimeout(function () {
  85056. successCallback(_this._reconstructedMesh);
  85057. }, 0);
  85058. });
  85059. };
  85060. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  85061. var _this = this;
  85062. var targetCount = ~~(this.triangles.length * settings.quality);
  85063. var deletedTriangles = 0;
  85064. var triangleCount = this.triangles.length;
  85065. var iterationFunction = function (iteration, callback) {
  85066. setTimeout(function () {
  85067. if (iteration % 5 === 0) {
  85068. _this.updateMesh(iteration === 0);
  85069. }
  85070. for (var i = 0; i < _this.triangles.length; ++i) {
  85071. _this.triangles[i].isDirty = false;
  85072. }
  85073. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  85074. var trianglesIterator = function (i) {
  85075. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  85076. var t = _this.triangles[tIdx];
  85077. if (!t)
  85078. return;
  85079. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  85080. return;
  85081. }
  85082. for (var j = 0; j < 3; ++j) {
  85083. if (t.error[j] < threshold) {
  85084. var deleted0 = [];
  85085. var deleted1 = [];
  85086. var v0 = t.vertices[j];
  85087. var v1 = t.vertices[(j + 1) % 3];
  85088. if (v0.isBorder || v1.isBorder)
  85089. continue;
  85090. var p = BABYLON.Vector3.Zero();
  85091. var n = BABYLON.Vector3.Zero();
  85092. var uv = BABYLON.Vector2.Zero();
  85093. var color = new BABYLON.Color4(0, 0, 0, 1);
  85094. _this.calculateError(v0, v1, p, n, uv, color);
  85095. var delTr = new Array();
  85096. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  85097. continue;
  85098. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  85099. continue;
  85100. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  85101. continue;
  85102. var uniqueArray = new Array();
  85103. delTr.forEach(function (deletedT) {
  85104. if (uniqueArray.indexOf(deletedT) === -1) {
  85105. deletedT.deletePending = true;
  85106. uniqueArray.push(deletedT);
  85107. }
  85108. });
  85109. if (uniqueArray.length % 2 !== 0) {
  85110. continue;
  85111. }
  85112. v0.q = v1.q.add(v0.q);
  85113. v0.updatePosition(p);
  85114. var tStart = _this.references.length;
  85115. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  85116. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  85117. var tCount = _this.references.length - tStart;
  85118. if (tCount <= v0.triangleCount) {
  85119. if (tCount) {
  85120. for (var c = 0; c < tCount; c++) {
  85121. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  85122. }
  85123. }
  85124. }
  85125. else {
  85126. v0.triangleStart = tStart;
  85127. }
  85128. v0.triangleCount = tCount;
  85129. break;
  85130. }
  85131. }
  85132. };
  85133. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  85134. }, 0);
  85135. };
  85136. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  85137. if (triangleCount - deletedTriangles <= targetCount)
  85138. loop.breakLoop();
  85139. else {
  85140. iterationFunction(loop.index, function () {
  85141. loop.executeNext();
  85142. });
  85143. }
  85144. }, function () {
  85145. setTimeout(function () {
  85146. //reconstruct this part of the mesh
  85147. _this.reconstructMesh(submeshIndex);
  85148. successCallback();
  85149. }, 0);
  85150. });
  85151. };
  85152. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  85153. var _this = this;
  85154. this.vertices = [];
  85155. this.triangles = [];
  85156. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85157. var indices = this._mesh.getIndices();
  85158. var submesh = this._mesh.subMeshes[submeshIndex];
  85159. var findInVertices = function (positionToSearch) {
  85160. if (optimizeMesh) {
  85161. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  85162. if (_this.vertices[ii].position.equals(positionToSearch)) {
  85163. return _this.vertices[ii];
  85164. }
  85165. }
  85166. }
  85167. return null;
  85168. };
  85169. var vertexReferences = [];
  85170. var vertexInit = function (i) {
  85171. if (!positionData) {
  85172. return;
  85173. }
  85174. var offset = i + submesh.verticesStart;
  85175. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  85176. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  85177. vertex.originalOffsets.push(offset);
  85178. if (vertex.id === _this.vertices.length) {
  85179. _this.vertices.push(vertex);
  85180. }
  85181. vertexReferences.push(vertex.id);
  85182. };
  85183. //var totalVertices = mesh.getTotalVertices();
  85184. var totalVertices = submesh.verticesCount;
  85185. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  85186. var indicesInit = function (i) {
  85187. if (!indices) {
  85188. return;
  85189. }
  85190. var offset = (submesh.indexStart / 3) + i;
  85191. var pos = (offset * 3);
  85192. var i0 = indices[pos + 0];
  85193. var i1 = indices[pos + 1];
  85194. var i2 = indices[pos + 2];
  85195. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  85196. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  85197. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  85198. var triangle = new DecimationTriangle([v0, v1, v2]);
  85199. triangle.originalOffset = pos;
  85200. _this.triangles.push(triangle);
  85201. };
  85202. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  85203. _this.init(callback);
  85204. });
  85205. });
  85206. };
  85207. QuadraticErrorSimplification.prototype.init = function (callback) {
  85208. var _this = this;
  85209. var triangleInit1 = function (i) {
  85210. var t = _this.triangles[i];
  85211. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  85212. for (var j = 0; j < 3; j++) {
  85213. 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))));
  85214. }
  85215. };
  85216. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  85217. var triangleInit2 = function (i) {
  85218. var t = _this.triangles[i];
  85219. for (var j = 0; j < 3; ++j) {
  85220. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  85221. }
  85222. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85223. };
  85224. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  85225. callback();
  85226. });
  85227. });
  85228. };
  85229. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  85230. var newTriangles = [];
  85231. var i;
  85232. for (i = 0; i < this.vertices.length; ++i) {
  85233. this.vertices[i].triangleCount = 0;
  85234. }
  85235. var t;
  85236. var j;
  85237. for (i = 0; i < this.triangles.length; ++i) {
  85238. if (!this.triangles[i].deleted) {
  85239. t = this.triangles[i];
  85240. for (j = 0; j < 3; ++j) {
  85241. t.vertices[j].triangleCount = 1;
  85242. }
  85243. newTriangles.push(t);
  85244. }
  85245. }
  85246. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  85247. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85248. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85249. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85250. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85251. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85252. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85253. var vertexCount = 0;
  85254. for (i = 0; i < this.vertices.length; ++i) {
  85255. var vertex = this.vertices[i];
  85256. vertex.id = vertexCount;
  85257. if (vertex.triangleCount) {
  85258. vertex.originalOffsets.forEach(function (originalOffset) {
  85259. if (!normalData) {
  85260. return;
  85261. }
  85262. newPositionData.push(vertex.position.x);
  85263. newPositionData.push(vertex.position.y);
  85264. newPositionData.push(vertex.position.z);
  85265. newNormalData.push(normalData[originalOffset * 3]);
  85266. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85267. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85268. if (uvs && uvs.length) {
  85269. newUVsData.push(uvs[(originalOffset * 2)]);
  85270. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85271. }
  85272. else if (colorsData && colorsData.length) {
  85273. newColorsData.push(colorsData[(originalOffset * 4)]);
  85274. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85275. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85276. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85277. }
  85278. ++vertexCount;
  85279. });
  85280. }
  85281. }
  85282. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85283. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85284. var submeshesArray = this._reconstructedMesh.subMeshes;
  85285. this._reconstructedMesh.subMeshes = [];
  85286. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85287. var originalIndices = this._mesh.getIndices();
  85288. for (i = 0; i < newTriangles.length; ++i) {
  85289. t = newTriangles[i]; //now get the new referencing point for each vertex
  85290. [0, 1, 2].forEach(function (idx) {
  85291. var id = originalIndices[t.originalOffset + idx];
  85292. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85293. if (offset < 0)
  85294. offset = 0;
  85295. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85296. });
  85297. }
  85298. //overwriting the old vertex buffers and indices.
  85299. this._reconstructedMesh.setIndices(newIndicesArray);
  85300. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85301. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85302. if (newUVsData.length > 0)
  85303. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85304. if (newColorsData.length > 0)
  85305. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85306. //create submesh
  85307. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85308. if (submeshIndex > 0) {
  85309. this._reconstructedMesh.subMeshes = [];
  85310. submeshesArray.forEach(function (submesh) {
  85311. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85312. });
  85313. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85314. }
  85315. };
  85316. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85317. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85318. this._reconstructedMesh.material = this._mesh.material;
  85319. this._reconstructedMesh.parent = this._mesh.parent;
  85320. this._reconstructedMesh.isVisible = false;
  85321. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85322. };
  85323. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85324. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85325. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85326. if (t.deleted)
  85327. continue;
  85328. var s = this.references[vertex1.triangleStart + i].vertexId;
  85329. var v1 = t.vertices[(s + 1) % 3];
  85330. var v2 = t.vertices[(s + 2) % 3];
  85331. if ((v1 === vertex2 || v2 === vertex2)) {
  85332. deletedArray[i] = true;
  85333. delTr.push(t);
  85334. continue;
  85335. }
  85336. var d1 = v1.position.subtract(point);
  85337. d1 = d1.normalize();
  85338. var d2 = v2.position.subtract(point);
  85339. d2 = d2.normalize();
  85340. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85341. return true;
  85342. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85343. deletedArray[i] = false;
  85344. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85345. return true;
  85346. }
  85347. return false;
  85348. };
  85349. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85350. var newDeleted = deletedTriangles;
  85351. for (var i = 0; i < vertex.triangleCount; ++i) {
  85352. var ref = this.references[vertex.triangleStart + i];
  85353. var t = this.triangles[ref.triangleId];
  85354. if (t.deleted)
  85355. continue;
  85356. if (deletedArray[i] && t.deletePending) {
  85357. t.deleted = true;
  85358. newDeleted++;
  85359. continue;
  85360. }
  85361. t.vertices[ref.vertexId] = origVertex;
  85362. t.isDirty = true;
  85363. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85364. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85365. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85366. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85367. this.references.push(ref);
  85368. }
  85369. return newDeleted;
  85370. };
  85371. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85372. for (var i = 0; i < this.vertices.length; ++i) {
  85373. var vCount = [];
  85374. var vId = [];
  85375. var v = this.vertices[i];
  85376. var j;
  85377. for (j = 0; j < v.triangleCount; ++j) {
  85378. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85379. for (var ii = 0; ii < 3; ii++) {
  85380. var ofs = 0;
  85381. var vv = triangle.vertices[ii];
  85382. while (ofs < vCount.length) {
  85383. if (vId[ofs] === vv.id)
  85384. break;
  85385. ++ofs;
  85386. }
  85387. if (ofs === vCount.length) {
  85388. vCount.push(1);
  85389. vId.push(vv.id);
  85390. }
  85391. else {
  85392. vCount[ofs]++;
  85393. }
  85394. }
  85395. }
  85396. for (j = 0; j < vCount.length; ++j) {
  85397. if (vCount[j] === 1) {
  85398. this.vertices[vId[j]].isBorder = true;
  85399. }
  85400. else {
  85401. this.vertices[vId[j]].isBorder = false;
  85402. }
  85403. }
  85404. }
  85405. };
  85406. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85407. if (identifyBorders === void 0) { identifyBorders = false; }
  85408. var i;
  85409. if (!identifyBorders) {
  85410. var newTrianglesVector = [];
  85411. for (i = 0; i < this.triangles.length; ++i) {
  85412. if (!this.triangles[i].deleted) {
  85413. newTrianglesVector.push(this.triangles[i]);
  85414. }
  85415. }
  85416. this.triangles = newTrianglesVector;
  85417. }
  85418. for (i = 0; i < this.vertices.length; ++i) {
  85419. this.vertices[i].triangleCount = 0;
  85420. this.vertices[i].triangleStart = 0;
  85421. }
  85422. var t;
  85423. var j;
  85424. var v;
  85425. for (i = 0; i < this.triangles.length; ++i) {
  85426. t = this.triangles[i];
  85427. for (j = 0; j < 3; ++j) {
  85428. v = t.vertices[j];
  85429. v.triangleCount++;
  85430. }
  85431. }
  85432. var tStart = 0;
  85433. for (i = 0; i < this.vertices.length; ++i) {
  85434. this.vertices[i].triangleStart = tStart;
  85435. tStart += this.vertices[i].triangleCount;
  85436. this.vertices[i].triangleCount = 0;
  85437. }
  85438. var newReferences = new Array(this.triangles.length * 3);
  85439. for (i = 0; i < this.triangles.length; ++i) {
  85440. t = this.triangles[i];
  85441. for (j = 0; j < 3; ++j) {
  85442. v = t.vertices[j];
  85443. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85444. v.triangleCount++;
  85445. }
  85446. }
  85447. this.references = newReferences;
  85448. if (identifyBorders) {
  85449. this.identifyBorder();
  85450. }
  85451. };
  85452. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85453. var x = point.x;
  85454. var y = point.y;
  85455. var z = point.z;
  85456. 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
  85457. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85458. };
  85459. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85460. var q = vertex1.q.add(vertex2.q);
  85461. var border = vertex1.isBorder && vertex2.isBorder;
  85462. var error = 0;
  85463. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85464. if (qDet !== 0 && !border) {
  85465. if (!pointResult) {
  85466. pointResult = BABYLON.Vector3.Zero();
  85467. }
  85468. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85469. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85470. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85471. error = this.vertexError(q, pointResult);
  85472. }
  85473. else {
  85474. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85475. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85476. var error1 = this.vertexError(q, vertex1.position);
  85477. var error2 = this.vertexError(q, vertex2.position);
  85478. var error3 = this.vertexError(q, p3);
  85479. error = Math.min(error1, error2, error3);
  85480. if (error === error1) {
  85481. if (pointResult) {
  85482. pointResult.copyFrom(vertex1.position);
  85483. }
  85484. }
  85485. else if (error === error2) {
  85486. if (pointResult) {
  85487. pointResult.copyFrom(vertex2.position);
  85488. }
  85489. }
  85490. else {
  85491. if (pointResult) {
  85492. pointResult.copyFrom(p3);
  85493. }
  85494. }
  85495. }
  85496. return error;
  85497. };
  85498. return QuadraticErrorSimplification;
  85499. }());
  85500. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85501. })(BABYLON || (BABYLON = {}));
  85502. //# sourceMappingURL=babylon.meshSimplification.js.map
  85503. "use strict";
  85504. var BABYLON;
  85505. (function (BABYLON) {
  85506. var MeshLODLevel = /** @class */ (function () {
  85507. function MeshLODLevel(distance, mesh) {
  85508. this.distance = distance;
  85509. this.mesh = mesh;
  85510. }
  85511. return MeshLODLevel;
  85512. }());
  85513. BABYLON.MeshLODLevel = MeshLODLevel;
  85514. })(BABYLON || (BABYLON = {}));
  85515. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85516. "use strict";
  85517. var BABYLON;
  85518. (function (BABYLON) {
  85519. /**
  85520. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85521. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85522. */
  85523. var SceneOptimization = /** @class */ (function () {
  85524. /**
  85525. * Creates the SceneOptimization object
  85526. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85527. * @param desc defines the description associated with the optimization
  85528. */
  85529. function SceneOptimization(
  85530. /**
  85531. * Defines the priority of this optimization (0 by default which means first in the list)
  85532. */
  85533. priority) {
  85534. if (priority === void 0) { priority = 0; }
  85535. this.priority = priority;
  85536. }
  85537. /**
  85538. * Gets a string describing the action executed by the current optimization
  85539. * @returns description string
  85540. */
  85541. SceneOptimization.prototype.getDescription = function () {
  85542. return "";
  85543. };
  85544. /**
  85545. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85546. * @param scene defines the current scene where to apply this optimization
  85547. * @param optimizer defines the current optimizer
  85548. * @returns true if everything that can be done was applied
  85549. */
  85550. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85551. return true;
  85552. };
  85553. ;
  85554. return SceneOptimization;
  85555. }());
  85556. BABYLON.SceneOptimization = SceneOptimization;
  85557. /**
  85558. * Defines an optimization used to reduce the size of render target textures
  85559. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85560. */
  85561. var TextureOptimization = /** @class */ (function (_super) {
  85562. __extends(TextureOptimization, _super);
  85563. /**
  85564. * Creates the TextureOptimization object
  85565. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85566. * @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
  85567. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85568. */
  85569. function TextureOptimization(
  85570. /**
  85571. * Defines the priority of this optimization (0 by default which means first in the list)
  85572. */
  85573. priority,
  85574. /**
  85575. * 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
  85576. */
  85577. maximumSize,
  85578. /**
  85579. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85580. */
  85581. step) {
  85582. if (priority === void 0) { priority = 0; }
  85583. if (maximumSize === void 0) { maximumSize = 1024; }
  85584. if (step === void 0) { step = 0.5; }
  85585. var _this = _super.call(this, priority) || this;
  85586. _this.priority = priority;
  85587. _this.maximumSize = maximumSize;
  85588. _this.step = step;
  85589. return _this;
  85590. }
  85591. /**
  85592. * Gets a string describing the action executed by the current optimization
  85593. * @returns description string
  85594. */
  85595. TextureOptimization.prototype.getDescription = function () {
  85596. return "Reducing render target texture size to " + this.maximumSize;
  85597. };
  85598. /**
  85599. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85600. * @param scene defines the current scene where to apply this optimization
  85601. * @param optimizer defines the current optimizer
  85602. * @returns true if everything that can be done was applied
  85603. */
  85604. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85605. var allDone = true;
  85606. for (var index = 0; index < scene.textures.length; index++) {
  85607. var texture = scene.textures[index];
  85608. if (!texture.canRescale || texture.getContext) {
  85609. continue;
  85610. }
  85611. var currentSize = texture.getSize();
  85612. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85613. if (maxDimension > this.maximumSize) {
  85614. texture.scale(this.step);
  85615. allDone = false;
  85616. }
  85617. }
  85618. return allDone;
  85619. };
  85620. return TextureOptimization;
  85621. }(SceneOptimization));
  85622. BABYLON.TextureOptimization = TextureOptimization;
  85623. /**
  85624. * Defines an optimization used to increase or decrease the rendering resolution
  85625. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85626. */
  85627. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85628. __extends(HardwareScalingOptimization, _super);
  85629. /**
  85630. * Creates the HardwareScalingOptimization object
  85631. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85632. * @param maximumScale defines the maximum scale to use (2 by default)
  85633. * @param step defines the step to use between two passes (0.5 by default)
  85634. */
  85635. function HardwareScalingOptimization(
  85636. /**
  85637. * Defines the priority of this optimization (0 by default which means first in the list)
  85638. */
  85639. priority,
  85640. /**
  85641. * Defines the maximum scale to use (2 by default)
  85642. */
  85643. maximumScale,
  85644. /**
  85645. * Defines the step to use between two passes (0.5 by default)
  85646. */
  85647. step) {
  85648. if (priority === void 0) { priority = 0; }
  85649. if (maximumScale === void 0) { maximumScale = 2; }
  85650. if (step === void 0) { step = 0.25; }
  85651. var _this = _super.call(this, priority) || this;
  85652. _this.priority = priority;
  85653. _this.maximumScale = maximumScale;
  85654. _this.step = step;
  85655. _this._currentScale = -1;
  85656. _this._directionOffset = 1;
  85657. return _this;
  85658. }
  85659. /**
  85660. * Gets a string describing the action executed by the current optimization
  85661. * @return description string
  85662. */
  85663. HardwareScalingOptimization.prototype.getDescription = function () {
  85664. return "Setting hardware scaling level to " + this._currentScale;
  85665. };
  85666. /**
  85667. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85668. * @param scene defines the current scene where to apply this optimization
  85669. * @param optimizer defines the current optimizer
  85670. * @returns true if everything that can be done was applied
  85671. */
  85672. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85673. if (this._currentScale === -1) {
  85674. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85675. if (this._currentScale > this.maximumScale) {
  85676. this._directionOffset = -1;
  85677. }
  85678. }
  85679. this._currentScale += this._directionOffset * this.step;
  85680. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85681. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85682. };
  85683. ;
  85684. return HardwareScalingOptimization;
  85685. }(SceneOptimization));
  85686. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85687. /**
  85688. * Defines an optimization used to remove shadows
  85689. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85690. */
  85691. var ShadowsOptimization = /** @class */ (function (_super) {
  85692. __extends(ShadowsOptimization, _super);
  85693. function ShadowsOptimization() {
  85694. return _super !== null && _super.apply(this, arguments) || this;
  85695. }
  85696. /**
  85697. * Gets a string describing the action executed by the current optimization
  85698. * @return description string
  85699. */
  85700. ShadowsOptimization.prototype.getDescription = function () {
  85701. return "Turning shadows on/off";
  85702. };
  85703. /**
  85704. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85705. * @param scene defines the current scene where to apply this optimization
  85706. * @param optimizer defines the current optimizer
  85707. * @returns true if everything that can be done was applied
  85708. */
  85709. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85710. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85711. return true;
  85712. };
  85713. ;
  85714. return ShadowsOptimization;
  85715. }(SceneOptimization));
  85716. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85717. /**
  85718. * Defines an optimization used to turn post-processes off
  85719. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85720. */
  85721. var PostProcessesOptimization = /** @class */ (function (_super) {
  85722. __extends(PostProcessesOptimization, _super);
  85723. function PostProcessesOptimization() {
  85724. return _super !== null && _super.apply(this, arguments) || this;
  85725. }
  85726. /**
  85727. * Gets a string describing the action executed by the current optimization
  85728. * @return description string
  85729. */
  85730. PostProcessesOptimization.prototype.getDescription = function () {
  85731. return "Turning post-processes on/off";
  85732. };
  85733. /**
  85734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85735. * @param scene defines the current scene where to apply this optimization
  85736. * @param optimizer defines the current optimizer
  85737. * @returns true if everything that can be done was applied
  85738. */
  85739. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85740. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85741. return true;
  85742. };
  85743. ;
  85744. return PostProcessesOptimization;
  85745. }(SceneOptimization));
  85746. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85747. /**
  85748. * Defines an optimization used to turn lens flares off
  85749. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85750. */
  85751. var LensFlaresOptimization = /** @class */ (function (_super) {
  85752. __extends(LensFlaresOptimization, _super);
  85753. function LensFlaresOptimization() {
  85754. return _super !== null && _super.apply(this, arguments) || this;
  85755. }
  85756. /**
  85757. * Gets a string describing the action executed by the current optimization
  85758. * @return description string
  85759. */
  85760. LensFlaresOptimization.prototype.getDescription = function () {
  85761. return "Turning lens flares on/off";
  85762. };
  85763. /**
  85764. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85765. * @param scene defines the current scene where to apply this optimization
  85766. * @param optimizer defines the current optimizer
  85767. * @returns true if everything that can be done was applied
  85768. */
  85769. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85770. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85771. return true;
  85772. };
  85773. ;
  85774. return LensFlaresOptimization;
  85775. }(SceneOptimization));
  85776. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85777. /**
  85778. * Defines an optimization based on user defined callback.
  85779. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85780. */
  85781. var CustomOptimization = /** @class */ (function (_super) {
  85782. __extends(CustomOptimization, _super);
  85783. function CustomOptimization() {
  85784. return _super !== null && _super.apply(this, arguments) || this;
  85785. }
  85786. /**
  85787. * Gets a string describing the action executed by the current optimization
  85788. * @returns description string
  85789. */
  85790. CustomOptimization.prototype.getDescription = function () {
  85791. if (this.onGetDescription) {
  85792. return this.onGetDescription();
  85793. }
  85794. return "Running user defined callback";
  85795. };
  85796. /**
  85797. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85798. * @param scene defines the current scene where to apply this optimization
  85799. * @param optimizer defines the current optimizer
  85800. * @returns true if everything that can be done was applied
  85801. */
  85802. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85803. if (this.onApply) {
  85804. return this.onApply(scene, optimizer);
  85805. }
  85806. return true;
  85807. };
  85808. ;
  85809. return CustomOptimization;
  85810. }(SceneOptimization));
  85811. BABYLON.CustomOptimization = CustomOptimization;
  85812. /**
  85813. * Defines an optimization used to turn particles off
  85814. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85815. */
  85816. var ParticlesOptimization = /** @class */ (function (_super) {
  85817. __extends(ParticlesOptimization, _super);
  85818. function ParticlesOptimization() {
  85819. return _super !== null && _super.apply(this, arguments) || this;
  85820. }
  85821. /**
  85822. * Gets a string describing the action executed by the current optimization
  85823. * @return description string
  85824. */
  85825. ParticlesOptimization.prototype.getDescription = function () {
  85826. return "Turning particles on/off";
  85827. };
  85828. /**
  85829. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85830. * @param scene defines the current scene where to apply this optimization
  85831. * @param optimizer defines the current optimizer
  85832. * @returns true if everything that can be done was applied
  85833. */
  85834. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85835. scene.particlesEnabled = optimizer.isInImprovementMode;
  85836. return true;
  85837. };
  85838. ;
  85839. return ParticlesOptimization;
  85840. }(SceneOptimization));
  85841. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85842. /**
  85843. * Defines an optimization used to turn render targets off
  85844. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85845. */
  85846. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85847. __extends(RenderTargetsOptimization, _super);
  85848. function RenderTargetsOptimization() {
  85849. return _super !== null && _super.apply(this, arguments) || this;
  85850. }
  85851. /**
  85852. * Gets a string describing the action executed by the current optimization
  85853. * @return description string
  85854. */
  85855. RenderTargetsOptimization.prototype.getDescription = function () {
  85856. return "Turning render targets off";
  85857. };
  85858. /**
  85859. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85860. * @param scene defines the current scene where to apply this optimization
  85861. * @param optimizer defines the current optimizer
  85862. * @returns true if everything that can be done was applied
  85863. */
  85864. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85865. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85866. return true;
  85867. };
  85868. ;
  85869. return RenderTargetsOptimization;
  85870. }(SceneOptimization));
  85871. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85872. /**
  85873. * Defines an optimization used to merge meshes with compatible materials
  85874. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85875. */
  85876. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85877. __extends(MergeMeshesOptimization, _super);
  85878. function MergeMeshesOptimization() {
  85879. var _this = _super !== null && _super.apply(this, arguments) || this;
  85880. _this._canBeMerged = function (abstractMesh) {
  85881. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85882. return false;
  85883. }
  85884. var mesh = abstractMesh;
  85885. if (!mesh.isVisible || !mesh.isEnabled()) {
  85886. return false;
  85887. }
  85888. if (mesh.instances.length > 0) {
  85889. return false;
  85890. }
  85891. if (mesh.skeleton || mesh.hasLODLevels) {
  85892. return false;
  85893. }
  85894. if (mesh.parent) {
  85895. return false;
  85896. }
  85897. return true;
  85898. };
  85899. return _this;
  85900. }
  85901. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85902. /**
  85903. * Gets or sets a boolean which defines if optimization octree has to be updated
  85904. */
  85905. get: function () {
  85906. return MergeMeshesOptimization._UpdateSelectionTree;
  85907. },
  85908. /**
  85909. * Gets or sets a boolean which defines if optimization octree has to be updated
  85910. */
  85911. set: function (value) {
  85912. MergeMeshesOptimization._UpdateSelectionTree = value;
  85913. },
  85914. enumerable: true,
  85915. configurable: true
  85916. });
  85917. /**
  85918. * Gets a string describing the action executed by the current optimization
  85919. * @return description string
  85920. */
  85921. MergeMeshesOptimization.prototype.getDescription = function () {
  85922. return "Merging similar meshes together";
  85923. };
  85924. /**
  85925. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85926. * @param scene defines the current scene where to apply this optimization
  85927. * @param optimizer defines the current optimizer
  85928. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85929. * @returns true if everything that can be done was applied
  85930. */
  85931. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85932. var globalPool = scene.meshes.slice(0);
  85933. var globalLength = globalPool.length;
  85934. for (var index = 0; index < globalLength; index++) {
  85935. var currentPool = new Array();
  85936. var current = globalPool[index];
  85937. // Checks
  85938. if (!this._canBeMerged(current)) {
  85939. continue;
  85940. }
  85941. currentPool.push(current);
  85942. // Find compatible meshes
  85943. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85944. var otherMesh = globalPool[subIndex];
  85945. if (!this._canBeMerged(otherMesh)) {
  85946. continue;
  85947. }
  85948. if (otherMesh.material !== current.material) {
  85949. continue;
  85950. }
  85951. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85952. continue;
  85953. }
  85954. currentPool.push(otherMesh);
  85955. globalLength--;
  85956. globalPool.splice(subIndex, 1);
  85957. subIndex--;
  85958. }
  85959. if (currentPool.length < 2) {
  85960. continue;
  85961. }
  85962. // Merge meshes
  85963. BABYLON.Mesh.MergeMeshes(currentPool);
  85964. }
  85965. if (updateSelectionTree != undefined) {
  85966. if (updateSelectionTree) {
  85967. scene.createOrUpdateSelectionOctree();
  85968. }
  85969. }
  85970. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85971. scene.createOrUpdateSelectionOctree();
  85972. }
  85973. return true;
  85974. };
  85975. ;
  85976. MergeMeshesOptimization._UpdateSelectionTree = false;
  85977. return MergeMeshesOptimization;
  85978. }(SceneOptimization));
  85979. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85980. /**
  85981. * Defines a list of options used by SceneOptimizer
  85982. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85983. */
  85984. var SceneOptimizerOptions = /** @class */ (function () {
  85985. /**
  85986. * Creates a new list of options used by SceneOptimizer
  85987. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85988. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85989. */
  85990. function SceneOptimizerOptions(
  85991. /**
  85992. * Defines the target frame rate to reach (60 by default)
  85993. */
  85994. targetFrameRate,
  85995. /**
  85996. * Defines the interval between two checkes (2000ms by default)
  85997. */
  85998. trackerDuration) {
  85999. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  86000. if (trackerDuration === void 0) { trackerDuration = 2000; }
  86001. this.targetFrameRate = targetFrameRate;
  86002. this.trackerDuration = trackerDuration;
  86003. /**
  86004. * Gets the list of optimizations to apply
  86005. */
  86006. this.optimizations = new Array();
  86007. }
  86008. /**
  86009. * Add a new optimization
  86010. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  86011. * @returns the current SceneOptimizerOptions
  86012. */
  86013. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  86014. this.optimizations.push(optimization);
  86015. return this;
  86016. };
  86017. /**
  86018. * Add a new custom optimization
  86019. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  86020. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  86021. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  86022. * @returns the current SceneOptimizerOptions
  86023. */
  86024. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  86025. if (priority === void 0) { priority = 0; }
  86026. var optimization = new CustomOptimization(priority);
  86027. optimization.onApply = onApply;
  86028. optimization.onGetDescription = onGetDescription;
  86029. this.optimizations.push(optimization);
  86030. return this;
  86031. };
  86032. /**
  86033. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  86034. * @param targetFrameRate defines the target frame rate (60 by default)
  86035. * @returns a SceneOptimizerOptions object
  86036. */
  86037. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  86038. var result = new SceneOptimizerOptions(targetFrameRate);
  86039. var priority = 0;
  86040. result.addOptimization(new MergeMeshesOptimization(priority));
  86041. result.addOptimization(new ShadowsOptimization(priority));
  86042. result.addOptimization(new LensFlaresOptimization(priority));
  86043. // Next priority
  86044. priority++;
  86045. result.addOptimization(new PostProcessesOptimization(priority));
  86046. result.addOptimization(new ParticlesOptimization(priority));
  86047. // Next priority
  86048. priority++;
  86049. result.addOptimization(new TextureOptimization(priority, 1024));
  86050. return result;
  86051. };
  86052. /**
  86053. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  86054. * @param targetFrameRate defines the target frame rate (60 by default)
  86055. * @returns a SceneOptimizerOptions object
  86056. */
  86057. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  86058. var result = new SceneOptimizerOptions(targetFrameRate);
  86059. var priority = 0;
  86060. result.addOptimization(new MergeMeshesOptimization(priority));
  86061. result.addOptimization(new ShadowsOptimization(priority));
  86062. result.addOptimization(new LensFlaresOptimization(priority));
  86063. // Next priority
  86064. priority++;
  86065. result.addOptimization(new PostProcessesOptimization(priority));
  86066. result.addOptimization(new ParticlesOptimization(priority));
  86067. // Next priority
  86068. priority++;
  86069. result.addOptimization(new TextureOptimization(priority, 512));
  86070. // Next priority
  86071. priority++;
  86072. result.addOptimization(new RenderTargetsOptimization(priority));
  86073. // Next priority
  86074. priority++;
  86075. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  86076. return result;
  86077. };
  86078. /**
  86079. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  86080. * @param targetFrameRate defines the target frame rate (60 by default)
  86081. * @returns a SceneOptimizerOptions object
  86082. */
  86083. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  86084. var result = new SceneOptimizerOptions(targetFrameRate);
  86085. var priority = 0;
  86086. result.addOptimization(new MergeMeshesOptimization(priority));
  86087. result.addOptimization(new ShadowsOptimization(priority));
  86088. result.addOptimization(new LensFlaresOptimization(priority));
  86089. // Next priority
  86090. priority++;
  86091. result.addOptimization(new PostProcessesOptimization(priority));
  86092. result.addOptimization(new ParticlesOptimization(priority));
  86093. // Next priority
  86094. priority++;
  86095. result.addOptimization(new TextureOptimization(priority, 256));
  86096. // Next priority
  86097. priority++;
  86098. result.addOptimization(new RenderTargetsOptimization(priority));
  86099. // Next priority
  86100. priority++;
  86101. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  86102. return result;
  86103. };
  86104. return SceneOptimizerOptions;
  86105. }());
  86106. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  86107. /**
  86108. * Class used to run optimizations in order to reach a target frame rate
  86109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86110. */
  86111. var SceneOptimizer = /** @class */ (function () {
  86112. /**
  86113. * Creates a new SceneOptimizer
  86114. * @param scene defines the scene to work on
  86115. * @param options defines the options to use with the SceneOptimizer
  86116. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  86117. * @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)
  86118. */
  86119. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  86120. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  86121. if (improvementMode === void 0) { improvementMode = false; }
  86122. var _this = this;
  86123. this._isRunning = false;
  86124. this._currentPriorityLevel = 0;
  86125. this._targetFrameRate = 60;
  86126. this._trackerDuration = 2000;
  86127. this._currentFrameRate = 0;
  86128. this._improvementMode = false;
  86129. /**
  86130. * Defines an observable called when the optimizer reaches the target frame rate
  86131. */
  86132. this.onSuccessObservable = new BABYLON.Observable();
  86133. /**
  86134. * Defines an observable called when the optimizer enables an optimization
  86135. */
  86136. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  86137. /**
  86138. * Defines an observable called when the optimizer is not able to reach the target frame rate
  86139. */
  86140. this.onFailureObservable = new BABYLON.Observable();
  86141. if (!options) {
  86142. this._options = new SceneOptimizerOptions();
  86143. }
  86144. else {
  86145. this._options = options;
  86146. }
  86147. if (this._options.targetFrameRate) {
  86148. this._targetFrameRate = this._options.targetFrameRate;
  86149. }
  86150. if (this._options.trackerDuration) {
  86151. this._trackerDuration = this._options.trackerDuration;
  86152. }
  86153. if (autoGeneratePriorities) {
  86154. var priority = 0;
  86155. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  86156. var optim = _a[_i];
  86157. optim.priority = priority++;
  86158. }
  86159. }
  86160. this._improvementMode = improvementMode;
  86161. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86162. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  86163. _this._sceneDisposeObserver = null;
  86164. _this.dispose();
  86165. });
  86166. }
  86167. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  86168. /**
  86169. * Gets a boolean indicating if the optimizer is in improvement mode
  86170. */
  86171. get: function () {
  86172. return this._improvementMode;
  86173. },
  86174. enumerable: true,
  86175. configurable: true
  86176. });
  86177. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  86178. /**
  86179. * Gets the current priority level (0 at start)
  86180. */
  86181. get: function () {
  86182. return this._currentPriorityLevel;
  86183. },
  86184. enumerable: true,
  86185. configurable: true
  86186. });
  86187. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  86188. /**
  86189. * Gets the current frame rate checked by the SceneOptimizer
  86190. */
  86191. get: function () {
  86192. return this._currentFrameRate;
  86193. },
  86194. enumerable: true,
  86195. configurable: true
  86196. });
  86197. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  86198. /**
  86199. * Gets or sets the current target frame rate (60 by default)
  86200. */
  86201. get: function () {
  86202. return this._targetFrameRate;
  86203. },
  86204. /**
  86205. * Gets or sets the current target frame rate (60 by default)
  86206. */
  86207. set: function (value) {
  86208. this._targetFrameRate = value;
  86209. },
  86210. enumerable: true,
  86211. configurable: true
  86212. });
  86213. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  86214. /**
  86215. * Gets or sets the current interval between two checks (every 2000ms by default)
  86216. */
  86217. get: function () {
  86218. return this._trackerDuration;
  86219. },
  86220. /**
  86221. * Gets or sets the current interval between two checks (every 2000ms by default)
  86222. */
  86223. set: function (value) {
  86224. this._trackerDuration = value;
  86225. },
  86226. enumerable: true,
  86227. configurable: true
  86228. });
  86229. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  86230. /**
  86231. * Gets the list of active optimizations
  86232. */
  86233. get: function () {
  86234. return this._options.optimizations;
  86235. },
  86236. enumerable: true,
  86237. configurable: true
  86238. });
  86239. /**
  86240. * Stops the current optimizer
  86241. */
  86242. SceneOptimizer.prototype.stop = function () {
  86243. this._isRunning = false;
  86244. };
  86245. /**
  86246. * Reset the optimizer to initial step (current priority level = 0)
  86247. */
  86248. SceneOptimizer.prototype.reset = function () {
  86249. this._currentPriorityLevel = 0;
  86250. };
  86251. /**
  86252. * Start the optimizer. By default it will try to reach a specific framerate
  86253. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86254. */
  86255. SceneOptimizer.prototype.start = function () {
  86256. var _this = this;
  86257. if (this._isRunning) {
  86258. return;
  86259. }
  86260. this._isRunning = true;
  86261. // Let's wait for the scene to be ready before running our check
  86262. this._scene.executeWhenReady(function () {
  86263. setTimeout(function () {
  86264. _this._checkCurrentState();
  86265. }, _this._trackerDuration);
  86266. });
  86267. };
  86268. SceneOptimizer.prototype._checkCurrentState = function () {
  86269. var _this = this;
  86270. if (!this._isRunning) {
  86271. return;
  86272. }
  86273. var scene = this._scene;
  86274. var options = this._options;
  86275. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86276. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86277. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86278. this._isRunning = false;
  86279. this.onSuccessObservable.notifyObservers(this);
  86280. return;
  86281. }
  86282. // Apply current level of optimizations
  86283. var allDone = true;
  86284. var noOptimizationApplied = true;
  86285. for (var index = 0; index < options.optimizations.length; index++) {
  86286. var optimization = options.optimizations[index];
  86287. if (optimization.priority === this._currentPriorityLevel) {
  86288. noOptimizationApplied = false;
  86289. allDone = allDone && optimization.apply(scene, this);
  86290. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86291. }
  86292. }
  86293. // If no optimization was applied, this is a failure :(
  86294. if (noOptimizationApplied) {
  86295. this._isRunning = false;
  86296. this.onFailureObservable.notifyObservers(this);
  86297. return;
  86298. }
  86299. // If all optimizations were done, move to next level
  86300. if (allDone) {
  86301. this._currentPriorityLevel++;
  86302. }
  86303. // Let's the system running for a specific amount of time before checking FPS
  86304. scene.executeWhenReady(function () {
  86305. setTimeout(function () {
  86306. _this._checkCurrentState();
  86307. }, _this._trackerDuration);
  86308. });
  86309. };
  86310. /**
  86311. * Release all resources
  86312. */
  86313. SceneOptimizer.prototype.dispose = function () {
  86314. this.stop();
  86315. this.onSuccessObservable.clear();
  86316. this.onFailureObservable.clear();
  86317. this.onNewOptimizationAppliedObservable.clear();
  86318. if (this._sceneDisposeObserver) {
  86319. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86320. }
  86321. };
  86322. /**
  86323. * Helper function to create a SceneOptimizer with one single line of code
  86324. * @param scene defines the scene to work on
  86325. * @param options defines the options to use with the SceneOptimizer
  86326. * @param onSuccess defines a callback to call on success
  86327. * @param onFailure defines a callback to call on failure
  86328. * @returns the new SceneOptimizer object
  86329. */
  86330. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86331. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86332. if (onSuccess) {
  86333. optimizer.onSuccessObservable.add(function () {
  86334. onSuccess();
  86335. });
  86336. }
  86337. if (onFailure) {
  86338. optimizer.onFailureObservable.add(function () {
  86339. onFailure();
  86340. });
  86341. }
  86342. optimizer.start();
  86343. return optimizer;
  86344. };
  86345. return SceneOptimizer;
  86346. }());
  86347. BABYLON.SceneOptimizer = SceneOptimizer;
  86348. })(BABYLON || (BABYLON = {}));
  86349. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86350. "use strict";
  86351. var BABYLON;
  86352. (function (BABYLON) {
  86353. var OutlineRenderer = /** @class */ (function () {
  86354. function OutlineRenderer(scene) {
  86355. this.zOffset = 1;
  86356. this._scene = scene;
  86357. }
  86358. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86359. var _this = this;
  86360. if (useOverlay === void 0) { useOverlay = false; }
  86361. var scene = this._scene;
  86362. var engine = this._scene.getEngine();
  86363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86364. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86365. return;
  86366. }
  86367. var mesh = subMesh.getRenderingMesh();
  86368. var material = subMesh.getMaterial();
  86369. if (!material || !scene.activeCamera) {
  86370. return;
  86371. }
  86372. engine.enableEffect(this._effect);
  86373. // Logarithmic depth
  86374. if (material.useLogarithmicDepth) {
  86375. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86376. }
  86377. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86378. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86379. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86380. // Bones
  86381. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86382. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86383. }
  86384. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86385. // Alpha test
  86386. if (material && material.needAlphaTesting()) {
  86387. var alphaTexture = material.getAlphaTestTexture();
  86388. if (alphaTexture) {
  86389. this._effect.setTexture("diffuseSampler", alphaTexture);
  86390. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86391. }
  86392. }
  86393. engine.setZOffset(-this.zOffset);
  86394. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86395. engine.setZOffset(0);
  86396. };
  86397. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86398. var defines = [];
  86399. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86400. var mesh = subMesh.getMesh();
  86401. var material = subMesh.getMaterial();
  86402. if (material) {
  86403. // Alpha test
  86404. if (material.needAlphaTesting()) {
  86405. defines.push("#define ALPHATEST");
  86406. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86407. attribs.push(BABYLON.VertexBuffer.UVKind);
  86408. defines.push("#define UV1");
  86409. }
  86410. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86411. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86412. defines.push("#define UV2");
  86413. }
  86414. }
  86415. //Logarithmic depth
  86416. if (material.useLogarithmicDepth) {
  86417. defines.push("#define LOGARITHMICDEPTH");
  86418. }
  86419. }
  86420. // Bones
  86421. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86422. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86423. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86424. if (mesh.numBoneInfluencers > 4) {
  86425. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86426. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86427. }
  86428. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86429. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86430. }
  86431. else {
  86432. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86433. }
  86434. // Instances
  86435. if (useInstances) {
  86436. defines.push("#define INSTANCES");
  86437. attribs.push("world0");
  86438. attribs.push("world1");
  86439. attribs.push("world2");
  86440. attribs.push("world3");
  86441. }
  86442. // Get correct effect
  86443. var join = defines.join("\n");
  86444. if (this._cachedDefines !== join) {
  86445. this._cachedDefines = join;
  86446. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86447. }
  86448. return this._effect.isReady();
  86449. };
  86450. return OutlineRenderer;
  86451. }());
  86452. BABYLON.OutlineRenderer = OutlineRenderer;
  86453. })(BABYLON || (BABYLON = {}));
  86454. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86455. "use strict";
  86456. var BABYLON;
  86457. (function (BABYLON) {
  86458. var FaceAdjacencies = /** @class */ (function () {
  86459. function FaceAdjacencies() {
  86460. this.edges = new Array();
  86461. this.edgesConnectedCount = 0;
  86462. }
  86463. return FaceAdjacencies;
  86464. }());
  86465. var EdgesRenderer = /** @class */ (function () {
  86466. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86467. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86468. if (epsilon === void 0) { epsilon = 0.95; }
  86469. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86470. this.edgesWidthScalerForOrthographic = 1000.0;
  86471. this.edgesWidthScalerForPerspective = 50.0;
  86472. this._linesPositions = new Array();
  86473. this._linesNormals = new Array();
  86474. this._linesIndices = new Array();
  86475. this._buffers = {};
  86476. this._checkVerticesInsteadOfIndices = false;
  86477. this._source = source;
  86478. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86479. this._epsilon = epsilon;
  86480. this._prepareRessources();
  86481. this._generateEdgesLines();
  86482. }
  86483. EdgesRenderer.prototype._prepareRessources = function () {
  86484. if (this._lineShader) {
  86485. return;
  86486. }
  86487. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86488. attributes: ["position", "normal"],
  86489. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86490. });
  86491. this._lineShader.disableDepthWrite = true;
  86492. this._lineShader.backFaceCulling = false;
  86493. };
  86494. EdgesRenderer.prototype._rebuild = function () {
  86495. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86496. if (buffer) {
  86497. buffer._rebuild();
  86498. }
  86499. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86500. if (buffer) {
  86501. buffer._rebuild();
  86502. }
  86503. var scene = this._source.getScene();
  86504. var engine = scene.getEngine();
  86505. this._ib = engine.createIndexBuffer(this._linesIndices);
  86506. };
  86507. EdgesRenderer.prototype.dispose = function () {
  86508. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86509. if (buffer) {
  86510. buffer.dispose();
  86511. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86512. }
  86513. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86514. if (buffer) {
  86515. buffer.dispose();
  86516. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86517. }
  86518. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86519. this._lineShader.dispose();
  86520. };
  86521. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86522. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86523. return 0;
  86524. }
  86525. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86526. return 1;
  86527. }
  86528. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86529. return 2;
  86530. }
  86531. return -1;
  86532. };
  86533. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86534. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86535. return 0;
  86536. }
  86537. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86538. return 1;
  86539. }
  86540. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86541. return 2;
  86542. }
  86543. return -1;
  86544. };
  86545. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86546. var needToCreateLine;
  86547. if (edge === undefined) {
  86548. needToCreateLine = true;
  86549. }
  86550. else {
  86551. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86552. needToCreateLine = dotProduct < this._epsilon;
  86553. }
  86554. if (needToCreateLine) {
  86555. var offset = this._linesPositions.length / 3;
  86556. var normal = p0.subtract(p1);
  86557. normal.normalize();
  86558. // Positions
  86559. this._linesPositions.push(p0.x);
  86560. this._linesPositions.push(p0.y);
  86561. this._linesPositions.push(p0.z);
  86562. this._linesPositions.push(p0.x);
  86563. this._linesPositions.push(p0.y);
  86564. this._linesPositions.push(p0.z);
  86565. this._linesPositions.push(p1.x);
  86566. this._linesPositions.push(p1.y);
  86567. this._linesPositions.push(p1.z);
  86568. this._linesPositions.push(p1.x);
  86569. this._linesPositions.push(p1.y);
  86570. this._linesPositions.push(p1.z);
  86571. // Normals
  86572. this._linesNormals.push(p1.x);
  86573. this._linesNormals.push(p1.y);
  86574. this._linesNormals.push(p1.z);
  86575. this._linesNormals.push(-1);
  86576. this._linesNormals.push(p1.x);
  86577. this._linesNormals.push(p1.y);
  86578. this._linesNormals.push(p1.z);
  86579. this._linesNormals.push(1);
  86580. this._linesNormals.push(p0.x);
  86581. this._linesNormals.push(p0.y);
  86582. this._linesNormals.push(p0.z);
  86583. this._linesNormals.push(-1);
  86584. this._linesNormals.push(p0.x);
  86585. this._linesNormals.push(p0.y);
  86586. this._linesNormals.push(p0.z);
  86587. this._linesNormals.push(1);
  86588. // Indices
  86589. this._linesIndices.push(offset);
  86590. this._linesIndices.push(offset + 1);
  86591. this._linesIndices.push(offset + 2);
  86592. this._linesIndices.push(offset);
  86593. this._linesIndices.push(offset + 2);
  86594. this._linesIndices.push(offset + 3);
  86595. }
  86596. };
  86597. EdgesRenderer.prototype._generateEdgesLines = function () {
  86598. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86599. var indices = this._source.getIndices();
  86600. if (!indices || !positions) {
  86601. return;
  86602. }
  86603. // First let's find adjacencies
  86604. var adjacencies = new Array();
  86605. var faceNormals = new Array();
  86606. var index;
  86607. var faceAdjacencies;
  86608. // Prepare faces
  86609. for (index = 0; index < indices.length; index += 3) {
  86610. faceAdjacencies = new FaceAdjacencies();
  86611. var p0Index = indices[index];
  86612. var p1Index = indices[index + 1];
  86613. var p2Index = indices[index + 2];
  86614. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86615. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86616. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86617. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86618. faceNormal.normalize();
  86619. faceNormals.push(faceNormal);
  86620. adjacencies.push(faceAdjacencies);
  86621. }
  86622. // Scan
  86623. for (index = 0; index < adjacencies.length; index++) {
  86624. faceAdjacencies = adjacencies[index];
  86625. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86626. var otherFaceAdjacencies = adjacencies[otherIndex];
  86627. if (faceAdjacencies.edgesConnectedCount === 3) {
  86628. break;
  86629. }
  86630. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86631. continue;
  86632. }
  86633. var otherP0 = indices[otherIndex * 3];
  86634. var otherP1 = indices[otherIndex * 3 + 1];
  86635. var otherP2 = indices[otherIndex * 3 + 2];
  86636. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86637. var otherEdgeIndex = 0;
  86638. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86639. continue;
  86640. }
  86641. switch (edgeIndex) {
  86642. case 0:
  86643. if (this._checkVerticesInsteadOfIndices) {
  86644. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86645. }
  86646. else {
  86647. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86648. }
  86649. break;
  86650. case 1:
  86651. if (this._checkVerticesInsteadOfIndices) {
  86652. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86653. }
  86654. else {
  86655. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86656. }
  86657. break;
  86658. case 2:
  86659. if (this._checkVerticesInsteadOfIndices) {
  86660. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86661. }
  86662. else {
  86663. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86664. }
  86665. break;
  86666. }
  86667. if (otherEdgeIndex === -1) {
  86668. continue;
  86669. }
  86670. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86671. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86672. faceAdjacencies.edgesConnectedCount++;
  86673. otherFaceAdjacencies.edgesConnectedCount++;
  86674. if (faceAdjacencies.edgesConnectedCount === 3) {
  86675. break;
  86676. }
  86677. }
  86678. }
  86679. }
  86680. // Create lines
  86681. for (index = 0; index < adjacencies.length; index++) {
  86682. // 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
  86683. var current = adjacencies[index];
  86684. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86685. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86686. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86687. }
  86688. // Merge into a single mesh
  86689. var engine = this._source.getScene().getEngine();
  86690. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86691. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86692. this._ib = engine.createIndexBuffer(this._linesIndices);
  86693. this._indicesCount = this._linesIndices.length;
  86694. };
  86695. EdgesRenderer.prototype.render = function () {
  86696. var scene = this._source.getScene();
  86697. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86698. return;
  86699. }
  86700. var engine = scene.getEngine();
  86701. this._lineShader._preBind();
  86702. // VBOs
  86703. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86704. scene.resetCachedMaterial();
  86705. this._lineShader.setColor4("color", this._source.edgesColor);
  86706. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86707. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86708. }
  86709. else {
  86710. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86711. }
  86712. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86713. this._lineShader.bind(this._source.getWorldMatrix());
  86714. // Draw order
  86715. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86716. this._lineShader.unbind();
  86717. engine.setDepthWrite(true);
  86718. };
  86719. return EdgesRenderer;
  86720. }());
  86721. BABYLON.EdgesRenderer = EdgesRenderer;
  86722. })(BABYLON || (BABYLON = {}));
  86723. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86724. "use strict";
  86725. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86726. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86727. s = arguments[i];
  86728. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86729. t[p] = s[p];
  86730. }
  86731. return t;
  86732. };
  86733. var BABYLON;
  86734. (function (BABYLON) {
  86735. /**
  86736. * The effect layer Helps adding post process effect blended with the main pass.
  86737. *
  86738. * This can be for instance use to generate glow or higlight effects on the scene.
  86739. *
  86740. * The effect layer class can not be used directly and is intented to inherited from to be
  86741. * customized per effects.
  86742. */
  86743. var EffectLayer = /** @class */ (function () {
  86744. /**
  86745. * Instantiates a new effect Layer and references it in the scene.
  86746. * @param name The name of the layer
  86747. * @param scene The scene to use the layer in
  86748. */
  86749. function EffectLayer(
  86750. /** The Friendly of the effect in the scene */
  86751. name, scene) {
  86752. this.name = name;
  86753. this._vertexBuffers = {};
  86754. this._maxSize = 0;
  86755. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86756. this._shouldRender = true;
  86757. this._postProcesses = [];
  86758. this._textures = [];
  86759. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86760. /**
  86761. * The clear color of the texture used to generate the glow map.
  86762. */
  86763. this.neutralColor = new BABYLON.Color4();
  86764. /**
  86765. * Specifies wether the highlight layer is enabled or not.
  86766. */
  86767. this.isEnabled = true;
  86768. /**
  86769. * An event triggered when the effect layer has been disposed.
  86770. */
  86771. this.onDisposeObservable = new BABYLON.Observable();
  86772. /**
  86773. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86774. */
  86775. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86776. /**
  86777. * An event triggered when the generated texture is being merged in the scene.
  86778. */
  86779. this.onBeforeComposeObservable = new BABYLON.Observable();
  86780. /**
  86781. * An event triggered when the generated texture has been merged in the scene.
  86782. */
  86783. this.onAfterComposeObservable = new BABYLON.Observable();
  86784. /**
  86785. * An event triggered when the efffect layer changes its size.
  86786. */
  86787. this.onSizeChangedObservable = new BABYLON.Observable();
  86788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86789. this._engine = scene.getEngine();
  86790. this._maxSize = this._engine.getCaps().maxTextureSize;
  86791. this._scene.effectLayers.push(this);
  86792. // Generate Buffers
  86793. this._generateIndexBuffer();
  86794. this._genrateVertexBuffer();
  86795. }
  86796. Object.defineProperty(EffectLayer.prototype, "camera", {
  86797. /**
  86798. * Gets the camera attached to the layer.
  86799. */
  86800. get: function () {
  86801. return this._effectLayerOptions.camera;
  86802. },
  86803. enumerable: true,
  86804. configurable: true
  86805. });
  86806. /**
  86807. * Initializes the effect layer with the required options.
  86808. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86809. */
  86810. EffectLayer.prototype._init = function (options) {
  86811. // Adapt options
  86812. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86813. this._setMainTextureSize();
  86814. this._createMainTexture();
  86815. this._createTextureAndPostProcesses();
  86816. this._mergeEffect = this._createMergeEffect();
  86817. };
  86818. /**
  86819. * Generates the index buffer of the full screen quad blending to the main canvas.
  86820. */
  86821. EffectLayer.prototype._generateIndexBuffer = function () {
  86822. // Indices
  86823. var indices = [];
  86824. indices.push(0);
  86825. indices.push(1);
  86826. indices.push(2);
  86827. indices.push(0);
  86828. indices.push(2);
  86829. indices.push(3);
  86830. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86831. };
  86832. /**
  86833. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86834. */
  86835. EffectLayer.prototype._genrateVertexBuffer = function () {
  86836. // VBO
  86837. var vertices = [];
  86838. vertices.push(1, 1);
  86839. vertices.push(-1, 1);
  86840. vertices.push(-1, -1);
  86841. vertices.push(1, -1);
  86842. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86844. };
  86845. /**
  86846. * Sets the main texture desired size which is the closest power of two
  86847. * of the engine canvas size.
  86848. */
  86849. EffectLayer.prototype._setMainTextureSize = function () {
  86850. if (this._effectLayerOptions.mainTextureFixedSize) {
  86851. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86852. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86853. }
  86854. else {
  86855. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86856. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86857. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86858. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86859. }
  86860. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86861. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86862. };
  86863. /**
  86864. * Creates the main texture for the effect layer.
  86865. */
  86866. EffectLayer.prototype._createMainTexture = function () {
  86867. var _this = this;
  86868. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86869. width: this._mainTextureDesiredSize.width,
  86870. height: this._mainTextureDesiredSize.height
  86871. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86872. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86873. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86874. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86875. this._mainTexture.anisotropicFilteringLevel = 1;
  86876. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86877. this._mainTexture.renderParticles = false;
  86878. this._mainTexture.renderList = null;
  86879. this._mainTexture.ignoreCameraViewport = true;
  86880. // Custom render function
  86881. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86882. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86883. var index;
  86884. var engine = _this._scene.getEngine();
  86885. if (depthOnlySubMeshes.length) {
  86886. engine.setColorWrite(false);
  86887. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86888. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86889. }
  86890. engine.setColorWrite(true);
  86891. }
  86892. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86893. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86894. }
  86895. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86896. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86897. }
  86898. for (index = 0; index < transparentSubMeshes.length; index++) {
  86899. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86900. }
  86901. };
  86902. this._mainTexture.onClearObservable.add(function (engine) {
  86903. engine.clear(_this.neutralColor, true, true, true);
  86904. });
  86905. };
  86906. /**
  86907. * Checks for the readiness of the element composing the layer.
  86908. * @param subMesh the mesh to check for
  86909. * @param useInstances specify wether or not to use instances to render the mesh
  86910. * @param emissiveTexture the associated emissive texture used to generate the glow
  86911. * @return true if ready otherwise, false
  86912. */
  86913. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86914. var material = subMesh.getMaterial();
  86915. if (!material) {
  86916. return false;
  86917. }
  86918. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86919. return false;
  86920. }
  86921. var defines = [];
  86922. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86923. var mesh = subMesh.getMesh();
  86924. var uv1 = false;
  86925. var uv2 = false;
  86926. // Alpha test
  86927. if (material && material.needAlphaTesting()) {
  86928. var alphaTexture = material.getAlphaTestTexture();
  86929. if (alphaTexture) {
  86930. defines.push("#define ALPHATEST");
  86931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86932. alphaTexture.coordinatesIndex === 1) {
  86933. defines.push("#define DIFFUSEUV2");
  86934. uv2 = true;
  86935. }
  86936. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86937. defines.push("#define DIFFUSEUV1");
  86938. uv1 = true;
  86939. }
  86940. }
  86941. }
  86942. // Emissive
  86943. if (emissiveTexture) {
  86944. defines.push("#define EMISSIVE");
  86945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86946. emissiveTexture.coordinatesIndex === 1) {
  86947. defines.push("#define EMISSIVEUV2");
  86948. uv2 = true;
  86949. }
  86950. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86951. defines.push("#define EMISSIVEUV1");
  86952. uv1 = true;
  86953. }
  86954. }
  86955. if (uv1) {
  86956. attribs.push(BABYLON.VertexBuffer.UVKind);
  86957. defines.push("#define UV1");
  86958. }
  86959. if (uv2) {
  86960. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86961. defines.push("#define UV2");
  86962. }
  86963. // Bones
  86964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86965. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86966. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86967. if (mesh.numBoneInfluencers > 4) {
  86968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86970. }
  86971. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86972. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86973. }
  86974. else {
  86975. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86976. }
  86977. // Morph targets
  86978. var manager = mesh.morphTargetManager;
  86979. var morphInfluencers = 0;
  86980. if (manager) {
  86981. if (manager.numInfluencers > 0) {
  86982. defines.push("#define MORPHTARGETS");
  86983. morphInfluencers = manager.numInfluencers;
  86984. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86985. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86986. }
  86987. }
  86988. // Instances
  86989. if (useInstances) {
  86990. defines.push("#define INSTANCES");
  86991. attribs.push("world0");
  86992. attribs.push("world1");
  86993. attribs.push("world2");
  86994. attribs.push("world3");
  86995. }
  86996. // Get correct effect
  86997. var join = defines.join("\n");
  86998. if (this._cachedDefines !== join) {
  86999. this._cachedDefines = join;
  87000. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  87001. }
  87002. return this._effectLayerMapGenerationEffect.isReady();
  87003. };
  87004. /**
  87005. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  87006. */
  87007. EffectLayer.prototype.render = function () {
  87008. var currentEffect = this._mergeEffect;
  87009. // Check
  87010. if (!currentEffect.isReady())
  87011. return;
  87012. for (var i = 0; i < this._postProcesses.length; i++) {
  87013. if (!this._postProcesses[i].isReady()) {
  87014. return;
  87015. }
  87016. }
  87017. var engine = this._scene.getEngine();
  87018. this.onBeforeComposeObservable.notifyObservers(this);
  87019. // Render
  87020. engine.enableEffect(currentEffect);
  87021. engine.setState(false);
  87022. // VBOs
  87023. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87024. // Cache
  87025. var previousAlphaMode = engine.getAlphaMode();
  87026. // Go Blend.
  87027. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  87028. // Blends the map on the main canvas.
  87029. this._internalRender(currentEffect);
  87030. // Restore Alpha
  87031. engine.setAlphaMode(previousAlphaMode);
  87032. this.onAfterComposeObservable.notifyObservers(this);
  87033. // Handle size changes.
  87034. var size = this._mainTexture.getSize();
  87035. this._setMainTextureSize();
  87036. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  87037. // Recreate RTT and post processes on size change.
  87038. this.onSizeChangedObservable.notifyObservers(this);
  87039. this._disposeTextureAndPostProcesses();
  87040. this._createMainTexture();
  87041. this._createTextureAndPostProcesses();
  87042. }
  87043. };
  87044. /**
  87045. * Determine if a given mesh will be used in the current effect.
  87046. * @param mesh mesh to test
  87047. * @returns true if the mesh will be used
  87048. */
  87049. EffectLayer.prototype.hasMesh = function (mesh) {
  87050. return true;
  87051. };
  87052. /**
  87053. * Returns true if the layer contains information to display, otherwise false.
  87054. * @returns true if the glow layer should be rendered
  87055. */
  87056. EffectLayer.prototype.shouldRender = function () {
  87057. return this.isEnabled && this._shouldRender;
  87058. };
  87059. /**
  87060. * Returns true if the mesh should render, otherwise false.
  87061. * @param mesh The mesh to render
  87062. * @returns true if it should render otherwise false
  87063. */
  87064. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  87065. return true;
  87066. };
  87067. /**
  87068. * Returns true if the mesh should render, otherwise false.
  87069. * @param mesh The mesh to render
  87070. * @returns true if it should render otherwise false
  87071. */
  87072. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  87073. return true;
  87074. };
  87075. /**
  87076. * Renders the submesh passed in parameter to the generation map.
  87077. */
  87078. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  87079. var _this = this;
  87080. if (!this.shouldRender()) {
  87081. return;
  87082. }
  87083. var material = subMesh.getMaterial();
  87084. var mesh = subMesh.getRenderingMesh();
  87085. var scene = this._scene;
  87086. var engine = scene.getEngine();
  87087. if (!material) {
  87088. return;
  87089. }
  87090. // Do not block in blend mode.
  87091. if (material.needAlphaBlendingForMesh(mesh)) {
  87092. return;
  87093. }
  87094. // Culling
  87095. engine.setState(material.backFaceCulling);
  87096. // Managing instances
  87097. var batch = mesh._getInstancesRenderList(subMesh._id);
  87098. if (batch.mustReturn) {
  87099. return;
  87100. }
  87101. // Early Exit per mesh
  87102. if (!this._shouldRenderMesh(mesh)) {
  87103. return;
  87104. }
  87105. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  87106. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  87107. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  87108. engine.enableEffect(this._effectLayerMapGenerationEffect);
  87109. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  87110. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  87111. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  87112. // Alpha test
  87113. if (material && material.needAlphaTesting()) {
  87114. var alphaTexture = material.getAlphaTestTexture();
  87115. if (alphaTexture) {
  87116. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  87117. var textureMatrix = alphaTexture.getTextureMatrix();
  87118. if (textureMatrix) {
  87119. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  87120. }
  87121. }
  87122. }
  87123. // Glow emissive only
  87124. if (this._emissiveTextureAndColor.texture) {
  87125. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  87126. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  87127. }
  87128. // Bones
  87129. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  87130. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  87131. }
  87132. // Morph targets
  87133. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  87134. // Draw
  87135. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  87136. }
  87137. else {
  87138. // Need to reset refresh rate of the shadowMap
  87139. this._mainTexture.resetRefreshCounter();
  87140. }
  87141. };
  87142. /**
  87143. * Rebuild the required buffers.
  87144. * @ignore Internal use only.
  87145. */
  87146. EffectLayer.prototype._rebuild = function () {
  87147. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87148. if (vb) {
  87149. vb._rebuild();
  87150. }
  87151. this._generateIndexBuffer();
  87152. };
  87153. /**
  87154. * Dispose only the render target textures and post process.
  87155. */
  87156. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  87157. this._mainTexture.dispose();
  87158. for (var i = 0; i < this._postProcesses.length; i++) {
  87159. if (this._postProcesses[i]) {
  87160. this._postProcesses[i].dispose();
  87161. }
  87162. }
  87163. this._postProcesses = [];
  87164. for (var i = 0; i < this._textures.length; i++) {
  87165. if (this._textures[i]) {
  87166. this._textures[i].dispose();
  87167. }
  87168. }
  87169. this._textures = [];
  87170. };
  87171. /**
  87172. * Dispose the highlight layer and free resources.
  87173. */
  87174. EffectLayer.prototype.dispose = function () {
  87175. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87176. if (vertexBuffer) {
  87177. vertexBuffer.dispose();
  87178. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87179. }
  87180. if (this._indexBuffer) {
  87181. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87182. this._indexBuffer = null;
  87183. }
  87184. // Clean textures and post processes
  87185. this._disposeTextureAndPostProcesses();
  87186. // Remove from scene
  87187. var index = this._scene.effectLayers.indexOf(this, 0);
  87188. if (index > -1) {
  87189. this._scene.effectLayers.splice(index, 1);
  87190. }
  87191. // Callback
  87192. this.onDisposeObservable.notifyObservers(this);
  87193. this.onDisposeObservable.clear();
  87194. this.onBeforeRenderMainTextureObservable.clear();
  87195. this.onBeforeComposeObservable.clear();
  87196. this.onAfterComposeObservable.clear();
  87197. this.onSizeChangedObservable.clear();
  87198. };
  87199. return EffectLayer;
  87200. }());
  87201. BABYLON.EffectLayer = EffectLayer;
  87202. })(BABYLON || (BABYLON = {}));
  87203. //# sourceMappingURL=babylon.effectLayer.js.map
  87204. "use strict";
  87205. var BABYLON;
  87206. (function (BABYLON) {
  87207. /**
  87208. * Special Glow Blur post process only blurring the alpha channel
  87209. * It enforces keeping the most luminous color in the color channel.
  87210. */
  87211. var GlowBlurPostProcess = /** @class */ (function (_super) {
  87212. __extends(GlowBlurPostProcess, _super);
  87213. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  87214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87215. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  87216. _this.direction = direction;
  87217. _this.kernel = kernel;
  87218. _this.onApplyObservable.add(function (effect) {
  87219. effect.setFloat2("screenSize", _this.width, _this.height);
  87220. effect.setVector2("direction", _this.direction);
  87221. effect.setFloat("blurWidth", _this.kernel);
  87222. });
  87223. return _this;
  87224. }
  87225. return GlowBlurPostProcess;
  87226. }(BABYLON.PostProcess));
  87227. /**
  87228. * The highlight layer Helps adding a glow effect around a mesh.
  87229. *
  87230. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87231. * glowy meshes to your scene.
  87232. *
  87233. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  87234. */
  87235. var HighlightLayer = /** @class */ (function (_super) {
  87236. __extends(HighlightLayer, _super);
  87237. /**
  87238. * Instantiates a new highlight Layer and references it to the scene..
  87239. * @param name The name of the layer
  87240. * @param scene The scene to use the layer in
  87241. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  87242. */
  87243. function HighlightLayer(name, scene, options) {
  87244. var _this = _super.call(this, name, scene) || this;
  87245. _this.name = name;
  87246. /**
  87247. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87248. */
  87249. _this.innerGlow = true;
  87250. /**
  87251. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87252. */
  87253. _this.outerGlow = true;
  87254. /**
  87255. * An event triggered when the highlight layer is being blurred.
  87256. */
  87257. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87258. /**
  87259. * An event triggered when the highlight layer has been blurred.
  87260. */
  87261. _this.onAfterBlurObservable = new BABYLON.Observable();
  87262. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87263. _this._meshes = {};
  87264. _this._excludedMeshes = {};
  87265. _this.neutralColor = HighlightLayer.NeutralColor;
  87266. // Warn on stencil
  87267. if (!_this._engine.isStencilEnable) {
  87268. 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 }");
  87269. }
  87270. // Adapt options
  87271. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87272. // Initialize the layer
  87273. _this._init({
  87274. alphaBlendingMode: _this._options.alphaBlendingMode,
  87275. camera: _this._options.camera,
  87276. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87277. mainTextureRatio: _this._options.mainTextureRatio
  87278. });
  87279. // Do not render as long as no meshes have been added
  87280. _this._shouldRender = false;
  87281. return _this;
  87282. }
  87283. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87284. /**
  87285. * Gets the horizontal size of the blur.
  87286. */
  87287. get: function () {
  87288. return this._horizontalBlurPostprocess.kernel;
  87289. },
  87290. /**
  87291. * Specifies the horizontal size of the blur.
  87292. */
  87293. set: function (value) {
  87294. this._horizontalBlurPostprocess.kernel = value;
  87295. },
  87296. enumerable: true,
  87297. configurable: true
  87298. });
  87299. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87300. /**
  87301. * Gets the vertical size of the blur.
  87302. */
  87303. get: function () {
  87304. return this._verticalBlurPostprocess.kernel;
  87305. },
  87306. /**
  87307. * Specifies the vertical size of the blur.
  87308. */
  87309. set: function (value) {
  87310. this._verticalBlurPostprocess.kernel = value;
  87311. },
  87312. enumerable: true,
  87313. configurable: true
  87314. });
  87315. /**
  87316. * Get the effect name of the layer.
  87317. * @return The effect name
  87318. */
  87319. HighlightLayer.prototype.getEffectName = function () {
  87320. return HighlightLayer.EffectName;
  87321. };
  87322. /**
  87323. * Create the merge effect. This is the shader use to blit the information back
  87324. * to the main canvas at the end of the scene rendering.
  87325. */
  87326. HighlightLayer.prototype._createMergeEffect = function () {
  87327. // Effect
  87328. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87329. };
  87330. /**
  87331. * Creates the render target textures and post processes used in the highlight layer.
  87332. */
  87333. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87334. var _this = this;
  87335. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87336. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87337. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87338. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87339. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87340. width: blurTextureWidth,
  87341. height: blurTextureHeight
  87342. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87343. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87344. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87345. this._blurTexture.anisotropicFilteringLevel = 16;
  87346. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87347. this._blurTexture.renderParticles = false;
  87348. this._blurTexture.ignoreCameraViewport = true;
  87349. this._textures = [this._blurTexture];
  87350. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87351. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87352. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87353. effect.setTexture("textureSampler", _this._mainTexture);
  87354. });
  87355. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87356. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87357. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87358. });
  87359. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87360. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87361. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87362. });
  87363. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87364. }
  87365. else {
  87366. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87367. width: blurTextureWidth,
  87368. height: blurTextureHeight
  87369. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87370. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87371. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87372. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87373. effect.setTexture("textureSampler", _this._mainTexture);
  87374. });
  87375. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87376. width: blurTextureWidth,
  87377. height: blurTextureHeight
  87378. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87379. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87380. }
  87381. this._mainTexture.onAfterUnbindObservable.add(function () {
  87382. _this.onBeforeBlurObservable.notifyObservers(_this);
  87383. var internalTexture = _this._blurTexture.getInternalTexture();
  87384. if (internalTexture) {
  87385. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87386. }
  87387. _this.onAfterBlurObservable.notifyObservers(_this);
  87388. });
  87389. // Prevent autoClear.
  87390. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87391. };
  87392. /**
  87393. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87394. */
  87395. HighlightLayer.prototype.needStencil = function () {
  87396. return true;
  87397. };
  87398. /**
  87399. * Checks for the readiness of the element composing the layer.
  87400. * @param subMesh the mesh to check for
  87401. * @param useInstances specify wether or not to use instances to render the mesh
  87402. * @param emissiveTexture the associated emissive texture used to generate the glow
  87403. * @return true if ready otherwise, false
  87404. */
  87405. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87406. var material = subMesh.getMaterial();
  87407. var mesh = subMesh.getRenderingMesh();
  87408. if (!material || !mesh || !this._meshes) {
  87409. return false;
  87410. }
  87411. var emissiveTexture = null;
  87412. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87413. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87414. emissiveTexture = material.emissiveTexture;
  87415. }
  87416. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87417. };
  87418. /**
  87419. * Implementation specific of rendering the generating effect on the main canvas.
  87420. * @param effect The effect used to render through
  87421. */
  87422. HighlightLayer.prototype._internalRender = function (effect) {
  87423. // Texture
  87424. effect.setTexture("textureSampler", this._blurTexture);
  87425. // Cache
  87426. var engine = this._engine;
  87427. var previousStencilBuffer = engine.getStencilBuffer();
  87428. var previousStencilFunction = engine.getStencilFunction();
  87429. var previousStencilMask = engine.getStencilMask();
  87430. var previousStencilOperationPass = engine.getStencilOperationPass();
  87431. var previousStencilOperationFail = engine.getStencilOperationFail();
  87432. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87433. var previousStencilReference = engine.getStencilFunctionReference();
  87434. // Stencil operations
  87435. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87436. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87437. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87438. // Draw order
  87439. engine.setStencilMask(0x00);
  87440. engine.setStencilBuffer(true);
  87441. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87442. // 2 passes inner outer
  87443. if (this.outerGlow) {
  87444. effect.setFloat("offset", 0);
  87445. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87446. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87447. }
  87448. if (this.innerGlow) {
  87449. effect.setFloat("offset", 1);
  87450. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87451. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87452. }
  87453. // Restore Cache
  87454. engine.setStencilFunction(previousStencilFunction);
  87455. engine.setStencilMask(previousStencilMask);
  87456. engine.setStencilBuffer(previousStencilBuffer);
  87457. engine.setStencilOperationPass(previousStencilOperationPass);
  87458. engine.setStencilOperationFail(previousStencilOperationFail);
  87459. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87460. engine.setStencilFunctionReference(previousStencilReference);
  87461. };
  87462. /**
  87463. * Returns true if the layer contains information to display, otherwise false.
  87464. */
  87465. HighlightLayer.prototype.shouldRender = function () {
  87466. if (_super.prototype.shouldRender.call(this)) {
  87467. return this._meshes ? true : false;
  87468. }
  87469. return false;
  87470. };
  87471. /**
  87472. * Returns true if the mesh should render, otherwise false.
  87473. * @param mesh The mesh to render
  87474. * @returns true if it should render otherwise false
  87475. */
  87476. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87477. // Excluded Mesh
  87478. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87479. return false;
  87480. }
  87481. ;
  87482. return true;
  87483. };
  87484. /**
  87485. * Sets the required values for both the emissive texture and and the main color.
  87486. */
  87487. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87488. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87489. if (highlightLayerMesh) {
  87490. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87491. }
  87492. else {
  87493. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87494. }
  87495. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87496. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87497. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87498. }
  87499. else {
  87500. this._emissiveTextureAndColor.texture = null;
  87501. }
  87502. };
  87503. /**
  87504. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87505. * @param mesh The mesh to exclude from the highlight layer
  87506. */
  87507. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87508. if (!this._excludedMeshes) {
  87509. return;
  87510. }
  87511. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87512. if (!meshExcluded) {
  87513. this._excludedMeshes[mesh.uniqueId] = {
  87514. mesh: mesh,
  87515. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87516. mesh.getEngine().setStencilBuffer(false);
  87517. }),
  87518. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87519. mesh.getEngine().setStencilBuffer(true);
  87520. }),
  87521. };
  87522. }
  87523. };
  87524. /**
  87525. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87526. * @param mesh The mesh to highlight
  87527. */
  87528. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87529. if (!this._excludedMeshes) {
  87530. return;
  87531. }
  87532. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87533. if (meshExcluded) {
  87534. if (meshExcluded.beforeRender) {
  87535. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87536. }
  87537. if (meshExcluded.afterRender) {
  87538. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87539. }
  87540. }
  87541. this._excludedMeshes[mesh.uniqueId] = null;
  87542. };
  87543. /**
  87544. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87545. * @param mesh mesh to test
  87546. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87547. */
  87548. HighlightLayer.prototype.hasMesh = function (mesh) {
  87549. if (!this._meshes) {
  87550. return false;
  87551. }
  87552. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87553. };
  87554. /**
  87555. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87556. * @param mesh The mesh to highlight
  87557. * @param color The color of the highlight
  87558. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87559. */
  87560. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87561. var _this = this;
  87562. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87563. if (!this._meshes) {
  87564. return;
  87565. }
  87566. var meshHighlight = this._meshes[mesh.uniqueId];
  87567. if (meshHighlight) {
  87568. meshHighlight.color = color;
  87569. }
  87570. else {
  87571. this._meshes[mesh.uniqueId] = {
  87572. mesh: mesh,
  87573. color: color,
  87574. // Lambda required for capture due to Observable this context
  87575. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87576. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87577. _this._defaultStencilReference(mesh);
  87578. }
  87579. else {
  87580. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87581. }
  87582. }),
  87583. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87584. glowEmissiveOnly: glowEmissiveOnly
  87585. };
  87586. }
  87587. this._shouldRender = true;
  87588. };
  87589. /**
  87590. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87591. * @param mesh The mesh to highlight
  87592. */
  87593. HighlightLayer.prototype.removeMesh = function (mesh) {
  87594. if (!this._meshes) {
  87595. return;
  87596. }
  87597. var meshHighlight = this._meshes[mesh.uniqueId];
  87598. if (meshHighlight) {
  87599. if (meshHighlight.observerHighlight) {
  87600. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87601. }
  87602. if (meshHighlight.observerDefault) {
  87603. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87604. }
  87605. delete this._meshes[mesh.uniqueId];
  87606. }
  87607. this._shouldRender = false;
  87608. for (var meshHighlightToCheck in this._meshes) {
  87609. if (this._meshes[meshHighlightToCheck]) {
  87610. this._shouldRender = true;
  87611. break;
  87612. }
  87613. }
  87614. };
  87615. /**
  87616. * Force the stencil to the normal expected value for none glowing parts
  87617. */
  87618. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87619. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87620. };
  87621. /**
  87622. * Free any resources and references associated to a mesh.
  87623. * Internal use
  87624. * @param mesh The mesh to free.
  87625. */
  87626. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87627. this.removeMesh(mesh);
  87628. this.removeExcludedMesh(mesh);
  87629. };
  87630. /**
  87631. * Dispose the highlight layer and free resources.
  87632. */
  87633. HighlightLayer.prototype.dispose = function () {
  87634. if (this._meshes) {
  87635. // Clean mesh references
  87636. for (var id in this._meshes) {
  87637. var meshHighlight = this._meshes[id];
  87638. if (meshHighlight && meshHighlight.mesh) {
  87639. if (meshHighlight.observerHighlight) {
  87640. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87641. }
  87642. if (meshHighlight.observerDefault) {
  87643. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87644. }
  87645. }
  87646. }
  87647. this._meshes = null;
  87648. }
  87649. if (this._excludedMeshes) {
  87650. for (var id in this._excludedMeshes) {
  87651. var meshHighlight = this._excludedMeshes[id];
  87652. if (meshHighlight) {
  87653. if (meshHighlight.beforeRender) {
  87654. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87655. }
  87656. if (meshHighlight.afterRender) {
  87657. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87658. }
  87659. }
  87660. }
  87661. this._excludedMeshes = null;
  87662. }
  87663. _super.prototype.dispose.call(this);
  87664. };
  87665. /**
  87666. * Effect Name of the highlight layer.
  87667. */
  87668. HighlightLayer.EffectName = "HighlightLayer";
  87669. /**
  87670. * The neutral color used during the preparation of the glow effect.
  87671. * This is black by default as the blend operation is a blend operation.
  87672. */
  87673. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87674. /**
  87675. * Stencil value used for glowing meshes.
  87676. */
  87677. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87678. /**
  87679. * Stencil value used for the other meshes in the scene.
  87680. */
  87681. HighlightLayer.NormalMeshStencilReference = 0x01;
  87682. return HighlightLayer;
  87683. }(BABYLON.EffectLayer));
  87684. BABYLON.HighlightLayer = HighlightLayer;
  87685. })(BABYLON || (BABYLON = {}));
  87686. //# sourceMappingURL=babylon.highlightLayer.js.map
  87687. "use strict";
  87688. var BABYLON;
  87689. (function (BABYLON) {
  87690. /**
  87691. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87692. *
  87693. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87694. * glowy meshes to your scene.
  87695. *
  87696. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87697. */
  87698. var GlowLayer = /** @class */ (function (_super) {
  87699. __extends(GlowLayer, _super);
  87700. /**
  87701. * Instantiates a new glow Layer and references it to the scene.
  87702. * @param name The name of the layer
  87703. * @param scene The scene to use the layer in
  87704. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87705. */
  87706. function GlowLayer(name, scene, options) {
  87707. var _this = _super.call(this, name, scene) || this;
  87708. _this.name = name;
  87709. _this._intensity = 1.0;
  87710. _this._includedOnlyMeshes = [];
  87711. _this._excludedMeshes = [];
  87712. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87713. // Adapt options
  87714. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87715. // Initialize the layer
  87716. _this._init({
  87717. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87718. camera: _this._options.camera,
  87719. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87720. mainTextureRatio: _this._options.mainTextureRatio
  87721. });
  87722. return _this;
  87723. }
  87724. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87725. /**
  87726. * Gets the kernel size of the blur.
  87727. */
  87728. get: function () {
  87729. return this._horizontalBlurPostprocess1.kernel;
  87730. },
  87731. /**
  87732. * Sets the kernel size of the blur.
  87733. */
  87734. set: function (value) {
  87735. this._horizontalBlurPostprocess1.kernel = value;
  87736. this._verticalBlurPostprocess1.kernel = value;
  87737. this._horizontalBlurPostprocess2.kernel = value;
  87738. this._verticalBlurPostprocess2.kernel = value;
  87739. },
  87740. enumerable: true,
  87741. configurable: true
  87742. });
  87743. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87744. /**
  87745. * Gets the glow intensity.
  87746. */
  87747. get: function () {
  87748. return this._intensity;
  87749. },
  87750. /**
  87751. * Sets the glow intensity.
  87752. */
  87753. set: function (value) {
  87754. this._intensity = value;
  87755. },
  87756. enumerable: true,
  87757. configurable: true
  87758. });
  87759. /**
  87760. * Get the effect name of the layer.
  87761. * @return The effect name
  87762. */
  87763. GlowLayer.prototype.getEffectName = function () {
  87764. return GlowLayer.EffectName;
  87765. };
  87766. /**
  87767. * Create the merge effect. This is the shader use to blit the information back
  87768. * to the main canvas at the end of the scene rendering.
  87769. */
  87770. GlowLayer.prototype._createMergeEffect = function () {
  87771. // Effect
  87772. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87773. };
  87774. /**
  87775. * Creates the render target textures and post processes used in the glow layer.
  87776. */
  87777. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87778. var _this = this;
  87779. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87780. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87781. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87782. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87783. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87784. width: blurTextureWidth,
  87785. height: blurTextureHeight
  87786. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87787. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87788. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87789. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87790. this._blurTexture1.renderParticles = false;
  87791. this._blurTexture1.ignoreCameraViewport = true;
  87792. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87793. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87794. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87795. width: blurTextureWidth2,
  87796. height: blurTextureHeight2
  87797. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87798. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87799. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87800. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87801. this._blurTexture2.renderParticles = false;
  87802. this._blurTexture2.ignoreCameraViewport = true;
  87803. this._textures = [this._blurTexture1, this._blurTexture2];
  87804. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87805. width: blurTextureWidth,
  87806. height: blurTextureHeight
  87807. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87808. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87809. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87810. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87811. effect.setTexture("textureSampler", _this._mainTexture);
  87812. });
  87813. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87814. width: blurTextureWidth,
  87815. height: blurTextureHeight
  87816. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87817. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87818. width: blurTextureWidth2,
  87819. height: blurTextureHeight2
  87820. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87821. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87822. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87823. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87824. effect.setTexture("textureSampler", _this._blurTexture1);
  87825. });
  87826. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87827. width: blurTextureWidth2,
  87828. height: blurTextureHeight2
  87829. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87830. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87831. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87832. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87833. this._mainTexture.samples = this._options.mainTextureSamples;
  87834. this._mainTexture.onAfterUnbindObservable.add(function () {
  87835. var internalTexture = _this._blurTexture1.getInternalTexture();
  87836. if (internalTexture) {
  87837. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87838. internalTexture = _this._blurTexture2.getInternalTexture();
  87839. if (internalTexture) {
  87840. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87841. }
  87842. }
  87843. });
  87844. // Prevent autoClear.
  87845. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87846. };
  87847. /**
  87848. * Checks for the readiness of the element composing the layer.
  87849. * @param subMesh the mesh to check for
  87850. * @param useInstances specify wether or not to use instances to render the mesh
  87851. * @param emissiveTexture the associated emissive texture used to generate the glow
  87852. * @return true if ready otherwise, false
  87853. */
  87854. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87855. var material = subMesh.getMaterial();
  87856. var mesh = subMesh.getRenderingMesh();
  87857. if (!material || !mesh) {
  87858. return false;
  87859. }
  87860. var emissiveTexture = material.emissiveTexture;
  87861. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87862. };
  87863. /**
  87864. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87865. */
  87866. GlowLayer.prototype.needStencil = function () {
  87867. return false;
  87868. };
  87869. /**
  87870. * Implementation specific of rendering the generating effect on the main canvas.
  87871. * @param effect The effect used to render through
  87872. */
  87873. GlowLayer.prototype._internalRender = function (effect) {
  87874. // Texture
  87875. effect.setTexture("textureSampler", this._blurTexture1);
  87876. effect.setTexture("textureSampler2", this._blurTexture2);
  87877. effect.setFloat("offset", this._intensity);
  87878. // Cache
  87879. var engine = this._engine;
  87880. var previousStencilBuffer = engine.getStencilBuffer();
  87881. // Draw order
  87882. engine.setStencilBuffer(false);
  87883. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87884. // Draw order
  87885. engine.setStencilBuffer(previousStencilBuffer);
  87886. };
  87887. /**
  87888. * Sets the required values for both the emissive texture and and the main color.
  87889. */
  87890. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87891. var textureLevel = 1.0;
  87892. if (this.customEmissiveTextureSelector) {
  87893. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87894. }
  87895. else {
  87896. if (material) {
  87897. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87898. if (this._emissiveTextureAndColor.texture) {
  87899. textureLevel = this._emissiveTextureAndColor.texture.level;
  87900. }
  87901. }
  87902. else {
  87903. this._emissiveTextureAndColor.texture = null;
  87904. }
  87905. }
  87906. if (this.customEmissiveColorSelector) {
  87907. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87908. }
  87909. else {
  87910. if (material.emissiveColor) {
  87911. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87912. }
  87913. else {
  87914. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87915. }
  87916. }
  87917. };
  87918. /**
  87919. * Returns true if the mesh should render, otherwise false.
  87920. * @param mesh The mesh to render
  87921. * @returns true if it should render otherwise false
  87922. */
  87923. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87924. return this.hasMesh(mesh);
  87925. };
  87926. /**
  87927. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87928. * @param mesh The mesh to exclude from the glow layer
  87929. */
  87930. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87931. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87932. this._excludedMeshes.push(mesh.uniqueId);
  87933. }
  87934. };
  87935. /**
  87936. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87937. * @param mesh The mesh to remove
  87938. */
  87939. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87940. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87941. if (index !== -1) {
  87942. this._excludedMeshes.splice(index, 1);
  87943. }
  87944. };
  87945. /**
  87946. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87947. * @param mesh The mesh to include in the glow layer
  87948. */
  87949. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87950. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87951. this._includedOnlyMeshes.push(mesh.uniqueId);
  87952. }
  87953. };
  87954. /**
  87955. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87956. * @param mesh The mesh to remove
  87957. */
  87958. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87959. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87960. if (index !== -1) {
  87961. this._includedOnlyMeshes.splice(index, 1);
  87962. }
  87963. };
  87964. /**
  87965. * Determine if a given mesh will be used in the glow layer
  87966. * @param mesh The mesh to test
  87967. * @returns true if the mesh will be highlighted by the current glow layer
  87968. */
  87969. GlowLayer.prototype.hasMesh = function (mesh) {
  87970. // Included Mesh
  87971. if (this._includedOnlyMeshes.length) {
  87972. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87973. }
  87974. ;
  87975. // Excluded Mesh
  87976. if (this._excludedMeshes.length) {
  87977. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87978. }
  87979. ;
  87980. return true;
  87981. };
  87982. /**
  87983. * Free any resources and references associated to a mesh.
  87984. * Internal use
  87985. * @param mesh The mesh to free.
  87986. */
  87987. GlowLayer.prototype._disposeMesh = function (mesh) {
  87988. this.removeIncludedOnlyMesh(mesh);
  87989. this.removeExcludedMesh(mesh);
  87990. };
  87991. /**
  87992. * Effect Name of the layer.
  87993. */
  87994. GlowLayer.EffectName = "GlowLayer";
  87995. /**
  87996. * The default blur kernel size used for the glow.
  87997. */
  87998. GlowLayer.DefaultBlurKernelSize = 32;
  87999. /**
  88000. * The default texture size ratio used for the glow.
  88001. */
  88002. GlowLayer.DefaultTextureRatio = 0.5;
  88003. return GlowLayer;
  88004. }(BABYLON.EffectLayer));
  88005. BABYLON.GlowLayer = GlowLayer;
  88006. })(BABYLON || (BABYLON = {}));
  88007. //# sourceMappingURL=babylon.glowLayer.js.map
  88008. "use strict";
  88009. var BABYLON;
  88010. (function (BABYLON) {
  88011. /**
  88012. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  88013. */
  88014. var AssetTaskState;
  88015. (function (AssetTaskState) {
  88016. /**
  88017. * Initialization
  88018. */
  88019. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  88020. /**
  88021. * Running
  88022. */
  88023. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  88024. /**
  88025. * Done
  88026. */
  88027. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  88028. /**
  88029. * Error
  88030. */
  88031. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  88032. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  88033. /**
  88034. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  88035. */
  88036. var AbstractAssetTask = /** @class */ (function () {
  88037. /**
  88038. * Creates a new {BABYLON.AssetsManager}
  88039. * @param name defines the name of the task
  88040. */
  88041. function AbstractAssetTask(
  88042. /**
  88043. * Task name
  88044. */ name) {
  88045. this.name = name;
  88046. this._isCompleted = false;
  88047. this._taskState = AssetTaskState.INIT;
  88048. }
  88049. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  88050. /**
  88051. * Get if the task is completed
  88052. */
  88053. get: function () {
  88054. return this._isCompleted;
  88055. },
  88056. enumerable: true,
  88057. configurable: true
  88058. });
  88059. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  88060. /**
  88061. * Gets the current state of the task
  88062. */
  88063. get: function () {
  88064. return this._taskState;
  88065. },
  88066. enumerable: true,
  88067. configurable: true
  88068. });
  88069. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  88070. /**
  88071. * Gets the current error object (if task is in error)
  88072. */
  88073. get: function () {
  88074. return this._errorObject;
  88075. },
  88076. enumerable: true,
  88077. configurable: true
  88078. });
  88079. /**
  88080. * Internal only
  88081. * @ignore
  88082. */
  88083. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  88084. if (this._errorObject) {
  88085. return;
  88086. }
  88087. this._errorObject = {
  88088. message: message,
  88089. exception: exception
  88090. };
  88091. };
  88092. /**
  88093. * Execute the current task
  88094. * @param scene defines the scene where you want your assets to be loaded
  88095. * @param onSuccess is a callback called when the task is successfully executed
  88096. * @param onError is a callback called if an error occurs
  88097. */
  88098. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88099. var _this = this;
  88100. this._taskState = AssetTaskState.RUNNING;
  88101. this.runTask(scene, function () {
  88102. _this.onDoneCallback(onSuccess, onError);
  88103. }, function (msg, exception) {
  88104. _this.onErrorCallback(onError, msg, exception);
  88105. });
  88106. };
  88107. /**
  88108. * Execute the current task
  88109. * @param scene defines the scene where you want your assets to be loaded
  88110. * @param onSuccess is a callback called when the task is successfully executed
  88111. * @param onError is a callback called if an error occurs
  88112. */
  88113. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88114. throw new Error("runTask is not implemented");
  88115. };
  88116. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  88117. this._taskState = AssetTaskState.ERROR;
  88118. this._errorObject = {
  88119. message: message,
  88120. exception: exception
  88121. };
  88122. if (this.onError) {
  88123. this.onError(this, message, exception);
  88124. }
  88125. onError();
  88126. };
  88127. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  88128. try {
  88129. this._taskState = AssetTaskState.DONE;
  88130. this._isCompleted = true;
  88131. if (this.onSuccess) {
  88132. this.onSuccess(this);
  88133. }
  88134. onSuccess();
  88135. }
  88136. catch (e) {
  88137. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  88138. }
  88139. };
  88140. return AbstractAssetTask;
  88141. }());
  88142. BABYLON.AbstractAssetTask = AbstractAssetTask;
  88143. /**
  88144. * Class used to share progress information about assets loading
  88145. */
  88146. var AssetsProgressEvent = /** @class */ (function () {
  88147. /**
  88148. * Creates a {BABYLON.AssetsProgressEvent}
  88149. * @param remainingCount defines the number of remaining tasks to process
  88150. * @param totalCount defines the total number of tasks
  88151. * @param task defines the task that was just processed
  88152. */
  88153. function AssetsProgressEvent(remainingCount, totalCount, task) {
  88154. this.remainingCount = remainingCount;
  88155. this.totalCount = totalCount;
  88156. this.task = task;
  88157. }
  88158. return AssetsProgressEvent;
  88159. }());
  88160. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  88161. /**
  88162. * Define a task used by {BABYLON.AssetsManager} to load meshes
  88163. */
  88164. var MeshAssetTask = /** @class */ (function (_super) {
  88165. __extends(MeshAssetTask, _super);
  88166. /**
  88167. * Creates a new {BABYLON.MeshAssetTask}
  88168. * @param name defines the name of the task
  88169. * @param meshesNames defines the list of mesh's names you want to load
  88170. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  88171. * @param sceneFilename defines the filename of the scene to load from
  88172. */
  88173. function MeshAssetTask(
  88174. /**
  88175. * Defines the name of the task
  88176. */
  88177. name,
  88178. /**
  88179. * Defines the list of mesh's names you want to load
  88180. */
  88181. meshesNames,
  88182. /**
  88183. * Defines the root url to use as a base to load your meshes and associated resources
  88184. */
  88185. rootUrl,
  88186. /**
  88187. * Defines the filename of the scene to load from
  88188. */
  88189. sceneFilename) {
  88190. var _this = _super.call(this, name) || this;
  88191. _this.name = name;
  88192. _this.meshesNames = meshesNames;
  88193. _this.rootUrl = rootUrl;
  88194. _this.sceneFilename = sceneFilename;
  88195. return _this;
  88196. }
  88197. /**
  88198. * Execute the current task
  88199. * @param scene defines the scene where you want your assets to be loaded
  88200. * @param onSuccess is a callback called when the task is successfully executed
  88201. * @param onError is a callback called if an error occurs
  88202. */
  88203. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88204. var _this = this;
  88205. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  88206. _this.loadedMeshes = meshes;
  88207. _this.loadedParticleSystems = particleSystems;
  88208. _this.loadedSkeletons = skeletons;
  88209. onSuccess();
  88210. }, null, function (scene, message, exception) {
  88211. onError(message, exception);
  88212. });
  88213. };
  88214. return MeshAssetTask;
  88215. }(AbstractAssetTask));
  88216. BABYLON.MeshAssetTask = MeshAssetTask;
  88217. /**
  88218. * Define a task used by {BABYLON.AssetsManager} to load text content
  88219. */
  88220. var TextFileAssetTask = /** @class */ (function (_super) {
  88221. __extends(TextFileAssetTask, _super);
  88222. /**
  88223. * Creates a new TextFileAssetTask object
  88224. * @param name defines the name of the task
  88225. * @param url defines the location of the file to load
  88226. */
  88227. function TextFileAssetTask(
  88228. /**
  88229. * Defines the name of the task
  88230. */
  88231. name,
  88232. /**
  88233. * Defines the location of the file to load
  88234. */
  88235. url) {
  88236. var _this = _super.call(this, name) || this;
  88237. _this.name = name;
  88238. _this.url = url;
  88239. return _this;
  88240. }
  88241. /**
  88242. * Execute the current task
  88243. * @param scene defines the scene where you want your assets to be loaded
  88244. * @param onSuccess is a callback called when the task is successfully executed
  88245. * @param onError is a callback called if an error occurs
  88246. */
  88247. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88248. var _this = this;
  88249. scene._loadFile(this.url, function (data) {
  88250. _this.text = data;
  88251. onSuccess();
  88252. }, undefined, false, false, function (request, exception) {
  88253. if (request) {
  88254. onError(request.status + " " + request.statusText, exception);
  88255. }
  88256. });
  88257. };
  88258. return TextFileAssetTask;
  88259. }(AbstractAssetTask));
  88260. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88261. /**
  88262. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88263. */
  88264. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88265. __extends(BinaryFileAssetTask, _super);
  88266. /**
  88267. * Creates a new BinaryFileAssetTask object
  88268. * @param name defines the name of the new task
  88269. * @param url defines the location of the file to load
  88270. */
  88271. function BinaryFileAssetTask(
  88272. /**
  88273. * Defines the name of the task
  88274. */
  88275. name,
  88276. /**
  88277. * Defines the location of the file to load
  88278. */
  88279. url) {
  88280. var _this = _super.call(this, name) || this;
  88281. _this.name = name;
  88282. _this.url = url;
  88283. return _this;
  88284. }
  88285. /**
  88286. * Execute the current task
  88287. * @param scene defines the scene where you want your assets to be loaded
  88288. * @param onSuccess is a callback called when the task is successfully executed
  88289. * @param onError is a callback called if an error occurs
  88290. */
  88291. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88292. var _this = this;
  88293. scene._loadFile(this.url, function (data) {
  88294. _this.data = data;
  88295. onSuccess();
  88296. }, undefined, true, true, function (request, exception) {
  88297. if (request) {
  88298. onError(request.status + " " + request.statusText, exception);
  88299. }
  88300. });
  88301. };
  88302. return BinaryFileAssetTask;
  88303. }(AbstractAssetTask));
  88304. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88305. /**
  88306. * Define a task used by {BABYLON.AssetsManager} to load images
  88307. */
  88308. var ImageAssetTask = /** @class */ (function (_super) {
  88309. __extends(ImageAssetTask, _super);
  88310. /**
  88311. * Creates a new ImageAssetTask
  88312. * @param name defines the name of the task
  88313. * @param url defines the location of the image to load
  88314. */
  88315. function ImageAssetTask(
  88316. /**
  88317. * Defines the name of the task
  88318. */
  88319. name,
  88320. /**
  88321. * Defines the location of the image to load
  88322. */
  88323. url) {
  88324. var _this = _super.call(this, name) || this;
  88325. _this.name = name;
  88326. _this.url = url;
  88327. return _this;
  88328. }
  88329. /**
  88330. * Execute the current task
  88331. * @param scene defines the scene where you want your assets to be loaded
  88332. * @param onSuccess is a callback called when the task is successfully executed
  88333. * @param onError is a callback called if an error occurs
  88334. */
  88335. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88336. var _this = this;
  88337. var img = new Image();
  88338. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88339. img.onload = function () {
  88340. _this.image = img;
  88341. onSuccess();
  88342. };
  88343. img.onerror = function (err) {
  88344. onError("Error loading image", err);
  88345. };
  88346. img.src = this.url;
  88347. };
  88348. return ImageAssetTask;
  88349. }(AbstractAssetTask));
  88350. BABYLON.ImageAssetTask = ImageAssetTask;
  88351. /**
  88352. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88353. */
  88354. var TextureAssetTask = /** @class */ (function (_super) {
  88355. __extends(TextureAssetTask, _super);
  88356. /**
  88357. * Creates a new TextureAssetTask object
  88358. * @param name defines the name of the task
  88359. * @param url defines the location of the file to load
  88360. * @param noMipmap defines if mipmap should not be generated (default is false)
  88361. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88362. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88363. */
  88364. function TextureAssetTask(
  88365. /**
  88366. * Defines the name of the task
  88367. */
  88368. name,
  88369. /**
  88370. * Defines the location of the file to load
  88371. */
  88372. url,
  88373. /**
  88374. * Defines if mipmap should not be generated (default is false)
  88375. */
  88376. noMipmap,
  88377. /**
  88378. * Defines if texture must be inverted on Y axis (default is false)
  88379. */
  88380. invertY,
  88381. /**
  88382. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88383. */
  88384. samplingMode) {
  88385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88386. var _this = _super.call(this, name) || this;
  88387. _this.name = name;
  88388. _this.url = url;
  88389. _this.noMipmap = noMipmap;
  88390. _this.invertY = invertY;
  88391. _this.samplingMode = samplingMode;
  88392. return _this;
  88393. }
  88394. /**
  88395. * Execute the current task
  88396. * @param scene defines the scene where you want your assets to be loaded
  88397. * @param onSuccess is a callback called when the task is successfully executed
  88398. * @param onError is a callback called if an error occurs
  88399. */
  88400. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88401. var onload = function () {
  88402. onSuccess();
  88403. };
  88404. var onerror = function (message, exception) {
  88405. onError(message, exception);
  88406. };
  88407. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88408. };
  88409. return TextureAssetTask;
  88410. }(AbstractAssetTask));
  88411. BABYLON.TextureAssetTask = TextureAssetTask;
  88412. /**
  88413. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88414. */
  88415. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88416. __extends(CubeTextureAssetTask, _super);
  88417. /**
  88418. * Creates a new CubeTextureAssetTask
  88419. * @param name defines the name of the task
  88420. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88421. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88422. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88423. * @param files defines the explicit list of files (undefined by default)
  88424. */
  88425. function CubeTextureAssetTask(
  88426. /**
  88427. * Defines the name of the task
  88428. */
  88429. name,
  88430. /**
  88431. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88432. */
  88433. url,
  88434. /**
  88435. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88436. */
  88437. extensions,
  88438. /**
  88439. * Defines if mipmaps should not be generated (default is false)
  88440. */
  88441. noMipmap,
  88442. /**
  88443. * Defines the explicit list of files (undefined by default)
  88444. */
  88445. files) {
  88446. var _this = _super.call(this, name) || this;
  88447. _this.name = name;
  88448. _this.url = url;
  88449. _this.extensions = extensions;
  88450. _this.noMipmap = noMipmap;
  88451. _this.files = files;
  88452. return _this;
  88453. }
  88454. /**
  88455. * Execute the current task
  88456. * @param scene defines the scene where you want your assets to be loaded
  88457. * @param onSuccess is a callback called when the task is successfully executed
  88458. * @param onError is a callback called if an error occurs
  88459. */
  88460. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88461. var onload = function () {
  88462. onSuccess();
  88463. };
  88464. var onerror = function (message, exception) {
  88465. onError(message, exception);
  88466. };
  88467. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88468. };
  88469. return CubeTextureAssetTask;
  88470. }(AbstractAssetTask));
  88471. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88472. /**
  88473. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88474. */
  88475. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88476. __extends(HDRCubeTextureAssetTask, _super);
  88477. /**
  88478. * Creates a new HDRCubeTextureAssetTask object
  88479. * @param name defines the name of the task
  88480. * @param url defines the location of the file to load
  88481. * @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.
  88482. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88483. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88484. * @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)
  88485. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88486. */
  88487. function HDRCubeTextureAssetTask(
  88488. /**
  88489. * Defines the name of the task
  88490. */
  88491. name,
  88492. /**
  88493. * Defines the location of the file to load
  88494. */
  88495. url,
  88496. /**
  88497. * 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.
  88498. */
  88499. size,
  88500. /**
  88501. * Defines if mipmaps should not be generated (default is false)
  88502. */
  88503. noMipmap,
  88504. /**
  88505. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88506. */
  88507. generateHarmonics,
  88508. /**
  88509. * 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)
  88510. */
  88511. useInGammaSpace,
  88512. /**
  88513. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88514. */
  88515. usePMREMGenerator) {
  88516. if (noMipmap === void 0) { noMipmap = false; }
  88517. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88518. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88519. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88520. var _this = _super.call(this, name) || this;
  88521. _this.name = name;
  88522. _this.url = url;
  88523. _this.size = size;
  88524. _this.noMipmap = noMipmap;
  88525. _this.generateHarmonics = generateHarmonics;
  88526. _this.useInGammaSpace = useInGammaSpace;
  88527. _this.usePMREMGenerator = usePMREMGenerator;
  88528. return _this;
  88529. }
  88530. /**
  88531. * Execute the current task
  88532. * @param scene defines the scene where you want your assets to be loaded
  88533. * @param onSuccess is a callback called when the task is successfully executed
  88534. * @param onError is a callback called if an error occurs
  88535. */
  88536. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88537. var onload = function () {
  88538. onSuccess();
  88539. };
  88540. var onerror = function (message, exception) {
  88541. onError(message, exception);
  88542. };
  88543. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88544. };
  88545. return HDRCubeTextureAssetTask;
  88546. }(AbstractAssetTask));
  88547. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88548. /**
  88549. * This class can be used to easily import assets into a scene
  88550. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88551. */
  88552. var AssetsManager = /** @class */ (function () {
  88553. /**
  88554. * Creates a new AssetsManager
  88555. * @param scene defines the scene to work on
  88556. */
  88557. function AssetsManager(scene) {
  88558. this._isLoading = false;
  88559. this._tasks = new Array();
  88560. this._waitingTasksCount = 0;
  88561. this._totalTasksCount = 0;
  88562. /**
  88563. * Observable called when all tasks are processed
  88564. */
  88565. this.onTaskSuccessObservable = new BABYLON.Observable();
  88566. /**
  88567. * Observable called when a task had an error
  88568. */
  88569. this.onTaskErrorObservable = new BABYLON.Observable();
  88570. /**
  88571. * Observable called when a task is successful
  88572. */
  88573. this.onTasksDoneObservable = new BABYLON.Observable();
  88574. /**
  88575. * Observable called when a task is done (whatever the result is)
  88576. */
  88577. this.onProgressObservable = new BABYLON.Observable();
  88578. /**
  88579. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88580. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88581. */
  88582. this.useDefaultLoadingScreen = true;
  88583. this._scene = scene;
  88584. }
  88585. /**
  88586. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88587. * @param taskName defines the name of the new task
  88588. * @param meshesNames defines the name of meshes to load
  88589. * @param rootUrl defines the root url to use to locate files
  88590. * @param sceneFilename defines the filename of the scene file
  88591. * @returns a new {BABYLON.MeshAssetTask} object
  88592. */
  88593. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88594. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88595. this._tasks.push(task);
  88596. return task;
  88597. };
  88598. /**
  88599. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88600. * @param taskName defines the name of the new task
  88601. * @param url defines the url of the file to load
  88602. * @returns a new {BABYLON.TextFileAssetTask} object
  88603. */
  88604. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88605. var task = new TextFileAssetTask(taskName, url);
  88606. this._tasks.push(task);
  88607. return task;
  88608. };
  88609. /**
  88610. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88611. * @param taskName defines the name of the new task
  88612. * @param url defines the url of the file to load
  88613. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88614. */
  88615. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88616. var task = new BinaryFileAssetTask(taskName, url);
  88617. this._tasks.push(task);
  88618. return task;
  88619. };
  88620. /**
  88621. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88622. * @param taskName defines the name of the new task
  88623. * @param url defines the url of the file to load
  88624. * @returns a new {BABYLON.ImageAssetTask} object
  88625. */
  88626. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88627. var task = new ImageAssetTask(taskName, url);
  88628. this._tasks.push(task);
  88629. return task;
  88630. };
  88631. /**
  88632. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88633. * @param taskName defines the name of the new task
  88634. * @param url defines the url of the file to load
  88635. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88636. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88637. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88638. * @returns a new {BABYLON.TextureAssetTask} object
  88639. */
  88640. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88642. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88643. this._tasks.push(task);
  88644. return task;
  88645. };
  88646. /**
  88647. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88648. * @param taskName defines the name of the new task
  88649. * @param url defines the url of the file to load
  88650. * @param extensions defines the extension to use to load the cube map (can be null)
  88651. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88652. * @param files defines the list of files to load (can be null)
  88653. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88654. */
  88655. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88656. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88657. this._tasks.push(task);
  88658. return task;
  88659. };
  88660. /**
  88661. *
  88662. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88663. * @param taskName defines the name of the new task
  88664. * @param url defines the url of the file to load
  88665. * @param size defines the size you want for the cubemap (can be null)
  88666. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88667. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88668. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88669. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88670. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88671. */
  88672. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88673. if (noMipmap === void 0) { noMipmap = false; }
  88674. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88675. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88676. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88677. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88678. this._tasks.push(task);
  88679. return task;
  88680. };
  88681. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88682. var _this = this;
  88683. this._waitingTasksCount--;
  88684. try {
  88685. if (task.taskState === AssetTaskState.DONE) {
  88686. // Let's remove successfull tasks
  88687. BABYLON.Tools.SetImmediate(function () {
  88688. var index = _this._tasks.indexOf(task);
  88689. if (index > -1) {
  88690. _this._tasks.splice(index, 1);
  88691. }
  88692. });
  88693. }
  88694. if (this.onProgress) {
  88695. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88696. }
  88697. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88698. }
  88699. catch (e) {
  88700. BABYLON.Tools.Error("Error running progress callbacks.");
  88701. console.log(e);
  88702. }
  88703. if (this._waitingTasksCount === 0) {
  88704. try {
  88705. if (this.onFinish) {
  88706. this.onFinish(this._tasks);
  88707. }
  88708. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88709. }
  88710. catch (e) {
  88711. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88712. console.log(e);
  88713. }
  88714. this._isLoading = false;
  88715. this._scene.getEngine().hideLoadingUI();
  88716. }
  88717. };
  88718. AssetsManager.prototype._runTask = function (task) {
  88719. var _this = this;
  88720. var done = function () {
  88721. try {
  88722. if (_this.onTaskSuccess) {
  88723. _this.onTaskSuccess(task);
  88724. }
  88725. _this.onTaskSuccessObservable.notifyObservers(task);
  88726. _this._decreaseWaitingTasksCount(task);
  88727. }
  88728. catch (e) {
  88729. error("Error executing task success callbacks", e);
  88730. }
  88731. };
  88732. var error = function (message, exception) {
  88733. task._setErrorObject(message, exception);
  88734. if (_this.onTaskError) {
  88735. _this.onTaskError(task);
  88736. }
  88737. _this.onTaskErrorObservable.notifyObservers(task);
  88738. _this._decreaseWaitingTasksCount(task);
  88739. };
  88740. task.run(this._scene, done, error);
  88741. };
  88742. /**
  88743. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88744. * @return the current instance of the {BABYLON.AssetsManager}
  88745. */
  88746. AssetsManager.prototype.reset = function () {
  88747. this._isLoading = false;
  88748. this._tasks = new Array();
  88749. return this;
  88750. };
  88751. /**
  88752. * Start the loading process
  88753. * @return the current instance of the {BABYLON.AssetsManager}
  88754. */
  88755. AssetsManager.prototype.load = function () {
  88756. if (this._isLoading) {
  88757. return this;
  88758. }
  88759. this._isLoading = true;
  88760. this._waitingTasksCount = this._tasks.length;
  88761. this._totalTasksCount = this._tasks.length;
  88762. if (this._waitingTasksCount === 0) {
  88763. this._isLoading = false;
  88764. if (this.onFinish) {
  88765. this.onFinish(this._tasks);
  88766. }
  88767. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88768. return this;
  88769. }
  88770. if (this.useDefaultLoadingScreen) {
  88771. this._scene.getEngine().displayLoadingUI();
  88772. }
  88773. for (var index = 0; index < this._tasks.length; index++) {
  88774. var task = this._tasks[index];
  88775. this._runTask(task);
  88776. }
  88777. return this;
  88778. };
  88779. return AssetsManager;
  88780. }());
  88781. BABYLON.AssetsManager = AssetsManager;
  88782. })(BABYLON || (BABYLON = {}));
  88783. //# sourceMappingURL=babylon.assetsManager.js.map
  88784. "use strict";
  88785. var BABYLON;
  88786. (function (BABYLON) {
  88787. var serializedGeometries = [];
  88788. var serializeGeometry = function (geometry, serializationGeometries) {
  88789. if (serializedGeometries[geometry.id]) {
  88790. return;
  88791. }
  88792. if (geometry.doNotSerialize) {
  88793. return;
  88794. }
  88795. if (geometry instanceof BABYLON.BoxGeometry) {
  88796. serializationGeometries.boxes.push(geometry.serialize());
  88797. }
  88798. else if (geometry instanceof BABYLON.SphereGeometry) {
  88799. serializationGeometries.spheres.push(geometry.serialize());
  88800. }
  88801. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88802. serializationGeometries.cylinders.push(geometry.serialize());
  88803. }
  88804. else if (geometry instanceof BABYLON.TorusGeometry) {
  88805. serializationGeometries.toruses.push(geometry.serialize());
  88806. }
  88807. else if (geometry instanceof BABYLON.GroundGeometry) {
  88808. serializationGeometries.grounds.push(geometry.serialize());
  88809. }
  88810. else if (geometry instanceof BABYLON.Plane) {
  88811. serializationGeometries.planes.push(geometry.serialize());
  88812. }
  88813. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88814. serializationGeometries.torusKnots.push(geometry.serialize());
  88815. }
  88816. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88817. throw new Error("Unknown primitive type");
  88818. }
  88819. else {
  88820. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88821. }
  88822. serializedGeometries[geometry.id] = true;
  88823. };
  88824. var serializeMesh = function (mesh, serializationScene) {
  88825. var serializationObject = {};
  88826. // Geometry
  88827. var geometry = mesh._geometry;
  88828. if (geometry) {
  88829. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88830. // 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
  88831. serializeGeometry(geometry, serializationScene.geometries);
  88832. }
  88833. }
  88834. // Custom
  88835. if (mesh.serialize) {
  88836. mesh.serialize(serializationObject);
  88837. }
  88838. return serializationObject;
  88839. };
  88840. var finalizeSingleMesh = function (mesh, serializationObject) {
  88841. //only works if the mesh is already loaded
  88842. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88843. //serialize material
  88844. if (mesh.material) {
  88845. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88846. serializationObject.materials = serializationObject.materials || [];
  88847. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88848. serializationObject.materials.push(mesh.material.serialize());
  88849. }
  88850. }
  88851. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88852. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88853. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88854. serializationObject.multiMaterials.push(mesh.material.serialize());
  88855. }
  88856. }
  88857. }
  88858. //serialize geometry
  88859. var geometry = mesh._geometry;
  88860. if (geometry) {
  88861. if (!serializationObject.geometries) {
  88862. serializationObject.geometries = {};
  88863. serializationObject.geometries.boxes = [];
  88864. serializationObject.geometries.spheres = [];
  88865. serializationObject.geometries.cylinders = [];
  88866. serializationObject.geometries.toruses = [];
  88867. serializationObject.geometries.grounds = [];
  88868. serializationObject.geometries.planes = [];
  88869. serializationObject.geometries.torusKnots = [];
  88870. serializationObject.geometries.vertexData = [];
  88871. }
  88872. serializeGeometry(geometry, serializationObject.geometries);
  88873. }
  88874. // Skeletons
  88875. if (mesh.skeleton) {
  88876. serializationObject.skeletons = serializationObject.skeletons || [];
  88877. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88878. }
  88879. //serialize the actual mesh
  88880. serializationObject.meshes = serializationObject.meshes || [];
  88881. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88882. }
  88883. };
  88884. var SceneSerializer = /** @class */ (function () {
  88885. function SceneSerializer() {
  88886. }
  88887. SceneSerializer.ClearCache = function () {
  88888. serializedGeometries = [];
  88889. };
  88890. SceneSerializer.Serialize = function (scene) {
  88891. var serializationObject = {};
  88892. SceneSerializer.ClearCache();
  88893. // Scene
  88894. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88895. serializationObject.autoClear = scene.autoClear;
  88896. serializationObject.clearColor = scene.clearColor.asArray();
  88897. serializationObject.ambientColor = scene.ambientColor.asArray();
  88898. serializationObject.gravity = scene.gravity.asArray();
  88899. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88900. serializationObject.workerCollisions = scene.workerCollisions;
  88901. // Fog
  88902. if (scene.fogMode && scene.fogMode !== 0) {
  88903. serializationObject.fogMode = scene.fogMode;
  88904. serializationObject.fogColor = scene.fogColor.asArray();
  88905. serializationObject.fogStart = scene.fogStart;
  88906. serializationObject.fogEnd = scene.fogEnd;
  88907. serializationObject.fogDensity = scene.fogDensity;
  88908. }
  88909. //Physics
  88910. if (scene.isPhysicsEnabled()) {
  88911. var physicEngine = scene.getPhysicsEngine();
  88912. if (physicEngine) {
  88913. serializationObject.physicsEnabled = true;
  88914. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88915. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88916. }
  88917. }
  88918. // Metadata
  88919. if (scene.metadata) {
  88920. serializationObject.metadata = scene.metadata;
  88921. }
  88922. // Morph targets
  88923. serializationObject.morphTargetManagers = [];
  88924. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88925. var abstractMesh = _a[_i];
  88926. var manager = abstractMesh.morphTargetManager;
  88927. if (manager) {
  88928. serializationObject.morphTargetManagers.push(manager.serialize());
  88929. }
  88930. }
  88931. // Lights
  88932. serializationObject.lights = [];
  88933. var index;
  88934. var light;
  88935. for (index = 0; index < scene.lights.length; index++) {
  88936. light = scene.lights[index];
  88937. if (!light.doNotSerialize) {
  88938. serializationObject.lights.push(light.serialize());
  88939. }
  88940. }
  88941. // Cameras
  88942. serializationObject.cameras = [];
  88943. for (index = 0; index < scene.cameras.length; index++) {
  88944. var camera = scene.cameras[index];
  88945. if (!camera.doNotSerialize) {
  88946. serializationObject.cameras.push(camera.serialize());
  88947. }
  88948. }
  88949. if (scene.activeCamera) {
  88950. serializationObject.activeCameraID = scene.activeCamera.id;
  88951. }
  88952. // Animations
  88953. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88954. // Materials
  88955. serializationObject.materials = [];
  88956. serializationObject.multiMaterials = [];
  88957. var material;
  88958. for (index = 0; index < scene.materials.length; index++) {
  88959. material = scene.materials[index];
  88960. if (!material.doNotSerialize) {
  88961. serializationObject.materials.push(material.serialize());
  88962. }
  88963. }
  88964. // MultiMaterials
  88965. serializationObject.multiMaterials = [];
  88966. for (index = 0; index < scene.multiMaterials.length; index++) {
  88967. var multiMaterial = scene.multiMaterials[index];
  88968. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88969. }
  88970. // Environment texture
  88971. if (scene.environmentTexture) {
  88972. serializationObject.environmentTexture = scene.environmentTexture.name;
  88973. }
  88974. // Skeletons
  88975. serializationObject.skeletons = [];
  88976. for (index = 0; index < scene.skeletons.length; index++) {
  88977. var skeleton = scene.skeletons[index];
  88978. if (!skeleton.doNotSerialize) {
  88979. serializationObject.skeletons.push(skeleton.serialize());
  88980. }
  88981. }
  88982. // Transform nodes
  88983. serializationObject.transformNodes = [];
  88984. for (index = 0; index < scene.transformNodes.length; index++) {
  88985. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88986. }
  88987. // Geometries
  88988. serializationObject.geometries = {};
  88989. serializationObject.geometries.boxes = [];
  88990. serializationObject.geometries.spheres = [];
  88991. serializationObject.geometries.cylinders = [];
  88992. serializationObject.geometries.toruses = [];
  88993. serializationObject.geometries.grounds = [];
  88994. serializationObject.geometries.planes = [];
  88995. serializationObject.geometries.torusKnots = [];
  88996. serializationObject.geometries.vertexData = [];
  88997. serializedGeometries = [];
  88998. var geometries = scene.getGeometries();
  88999. for (index = 0; index < geometries.length; index++) {
  89000. var geometry = geometries[index];
  89001. if (geometry.isReady()) {
  89002. serializeGeometry(geometry, serializationObject.geometries);
  89003. }
  89004. }
  89005. // Meshes
  89006. serializationObject.meshes = [];
  89007. for (index = 0; index < scene.meshes.length; index++) {
  89008. var abstractMesh = scene.meshes[index];
  89009. if (abstractMesh instanceof BABYLON.Mesh) {
  89010. var mesh = abstractMesh;
  89011. if (!mesh.doNotSerialize) {
  89012. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  89013. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  89014. }
  89015. }
  89016. }
  89017. }
  89018. // Particles Systems
  89019. serializationObject.particleSystems = [];
  89020. for (index = 0; index < scene.particleSystems.length; index++) {
  89021. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  89022. }
  89023. // Lens flares
  89024. serializationObject.lensFlareSystems = [];
  89025. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  89026. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  89027. }
  89028. // Shadows
  89029. serializationObject.shadowGenerators = [];
  89030. for (index = 0; index < scene.lights.length; index++) {
  89031. light = scene.lights[index];
  89032. var shadowGenerator = light.getShadowGenerator();
  89033. if (shadowGenerator) {
  89034. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  89035. }
  89036. }
  89037. // Action Manager
  89038. if (scene.actionManager) {
  89039. serializationObject.actions = scene.actionManager.serialize("scene");
  89040. }
  89041. // Audio
  89042. serializationObject.sounds = [];
  89043. for (index = 0; index < scene.soundTracks.length; index++) {
  89044. var soundtrack = scene.soundTracks[index];
  89045. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  89046. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  89047. }
  89048. }
  89049. return serializationObject;
  89050. };
  89051. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  89052. if (withParents === void 0) { withParents = false; }
  89053. if (withChildren === void 0) { withChildren = false; }
  89054. var serializationObject = {};
  89055. SceneSerializer.ClearCache();
  89056. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  89057. if (withParents || withChildren) {
  89058. //deliberate for loop! not for each, appended should be processed as well.
  89059. for (var i = 0; i < toSerialize.length; ++i) {
  89060. if (withChildren) {
  89061. toSerialize[i].getDescendants().forEach(function (node) {
  89062. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  89063. toSerialize.push(node);
  89064. }
  89065. });
  89066. }
  89067. //make sure the array doesn't contain the object already
  89068. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  89069. toSerialize.push(toSerialize[i].parent);
  89070. }
  89071. }
  89072. }
  89073. toSerialize.forEach(function (mesh) {
  89074. finalizeSingleMesh(mesh, serializationObject);
  89075. });
  89076. return serializationObject;
  89077. };
  89078. return SceneSerializer;
  89079. }());
  89080. BABYLON.SceneSerializer = SceneSerializer;
  89081. })(BABYLON || (BABYLON = {}));
  89082. //# sourceMappingURL=babylon.sceneSerializer.js.map
  89083. "use strict";
  89084. var BABYLON;
  89085. (function (BABYLON) {
  89086. var ReflectionProbe = /** @class */ (function () {
  89087. function ReflectionProbe(name, size, scene, generateMipMaps) {
  89088. if (generateMipMaps === void 0) { generateMipMaps = true; }
  89089. var _this = this;
  89090. this.name = name;
  89091. this._viewMatrix = BABYLON.Matrix.Identity();
  89092. this._target = BABYLON.Vector3.Zero();
  89093. this._add = BABYLON.Vector3.Zero();
  89094. this._invertYAxis = false;
  89095. this.position = BABYLON.Vector3.Zero();
  89096. this._scene = scene;
  89097. this._scene.reflectionProbes.push(this);
  89098. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  89099. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  89100. switch (faceIndex) {
  89101. case 0:
  89102. _this._add.copyFromFloats(1, 0, 0);
  89103. break;
  89104. case 1:
  89105. _this._add.copyFromFloats(-1, 0, 0);
  89106. break;
  89107. case 2:
  89108. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  89109. break;
  89110. case 3:
  89111. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  89112. break;
  89113. case 4:
  89114. _this._add.copyFromFloats(0, 0, 1);
  89115. break;
  89116. case 5:
  89117. _this._add.copyFromFloats(0, 0, -1);
  89118. break;
  89119. }
  89120. if (_this._attachedMesh) {
  89121. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  89122. }
  89123. _this.position.addToRef(_this._add, _this._target);
  89124. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  89125. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  89126. scene._forcedViewPosition = _this.position;
  89127. });
  89128. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  89129. scene._forcedViewPosition = null;
  89130. scene.updateTransformMatrix(true);
  89131. });
  89132. if (scene.activeCamera) {
  89133. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  89134. }
  89135. }
  89136. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  89137. get: function () {
  89138. return this._renderTargetTexture.samples;
  89139. },
  89140. set: function (value) {
  89141. this._renderTargetTexture.samples = value;
  89142. },
  89143. enumerable: true,
  89144. configurable: true
  89145. });
  89146. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  89147. get: function () {
  89148. return this._renderTargetTexture.refreshRate;
  89149. },
  89150. set: function (value) {
  89151. this._renderTargetTexture.refreshRate = value;
  89152. },
  89153. enumerable: true,
  89154. configurable: true
  89155. });
  89156. ReflectionProbe.prototype.getScene = function () {
  89157. return this._scene;
  89158. };
  89159. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  89160. get: function () {
  89161. return this._renderTargetTexture;
  89162. },
  89163. enumerable: true,
  89164. configurable: true
  89165. });
  89166. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  89167. get: function () {
  89168. return this._renderTargetTexture.renderList;
  89169. },
  89170. enumerable: true,
  89171. configurable: true
  89172. });
  89173. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  89174. this._attachedMesh = mesh;
  89175. };
  89176. /**
  89177. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  89178. *
  89179. * @param renderingGroupId The rendering group id corresponding to its index
  89180. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  89181. */
  89182. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  89183. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  89184. };
  89185. ReflectionProbe.prototype.dispose = function () {
  89186. var index = this._scene.reflectionProbes.indexOf(this);
  89187. if (index !== -1) {
  89188. // Remove from the scene if found
  89189. this._scene.reflectionProbes.splice(index, 1);
  89190. }
  89191. if (this._renderTargetTexture) {
  89192. this._renderTargetTexture.dispose();
  89193. this._renderTargetTexture = null;
  89194. }
  89195. };
  89196. return ReflectionProbe;
  89197. }());
  89198. BABYLON.ReflectionProbe = ReflectionProbe;
  89199. })(BABYLON || (BABYLON = {}));
  89200. //# sourceMappingURL=babylon.reflectionProbe.js.map
  89201. "use strict";
  89202. var BABYLON;
  89203. (function (BABYLON) {
  89204. var Layer = /** @class */ (function () {
  89205. function Layer(name, imgUrl, scene, isBackground, color) {
  89206. this.name = name;
  89207. this.scale = new BABYLON.Vector2(1, 1);
  89208. this.offset = new BABYLON.Vector2(0, 0);
  89209. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  89210. this.layerMask = 0x0FFFFFFF;
  89211. this._vertexBuffers = {};
  89212. // Events
  89213. /**
  89214. * An event triggered when the layer is disposed.
  89215. * @type {BABYLON.Observable}
  89216. */
  89217. this.onDisposeObservable = new BABYLON.Observable();
  89218. /**
  89219. * An event triggered before rendering the scene
  89220. * @type {BABYLON.Observable}
  89221. */
  89222. this.onBeforeRenderObservable = new BABYLON.Observable();
  89223. /**
  89224. * An event triggered after rendering the scene
  89225. * @type {BABYLON.Observable}
  89226. */
  89227. this.onAfterRenderObservable = new BABYLON.Observable();
  89228. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  89229. this.isBackground = isBackground === undefined ? true : isBackground;
  89230. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  89231. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  89232. this._scene.layers.push(this);
  89233. var engine = this._scene.getEngine();
  89234. // VBO
  89235. var vertices = [];
  89236. vertices.push(1, 1);
  89237. vertices.push(-1, 1);
  89238. vertices.push(-1, -1);
  89239. vertices.push(1, -1);
  89240. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89241. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89242. this._createIndexBuffer();
  89243. // Effects
  89244. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  89245. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  89246. }
  89247. Object.defineProperty(Layer.prototype, "onDispose", {
  89248. set: function (callback) {
  89249. if (this._onDisposeObserver) {
  89250. this.onDisposeObservable.remove(this._onDisposeObserver);
  89251. }
  89252. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89253. },
  89254. enumerable: true,
  89255. configurable: true
  89256. });
  89257. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89258. set: function (callback) {
  89259. if (this._onBeforeRenderObserver) {
  89260. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89261. }
  89262. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89263. },
  89264. enumerable: true,
  89265. configurable: true
  89266. });
  89267. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89268. set: function (callback) {
  89269. if (this._onAfterRenderObserver) {
  89270. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89271. }
  89272. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89273. },
  89274. enumerable: true,
  89275. configurable: true
  89276. });
  89277. Layer.prototype._createIndexBuffer = function () {
  89278. var engine = this._scene.getEngine();
  89279. // Indices
  89280. var indices = [];
  89281. indices.push(0);
  89282. indices.push(1);
  89283. indices.push(2);
  89284. indices.push(0);
  89285. indices.push(2);
  89286. indices.push(3);
  89287. this._indexBuffer = engine.createIndexBuffer(indices);
  89288. };
  89289. Layer.prototype._rebuild = function () {
  89290. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89291. if (vb) {
  89292. vb._rebuild();
  89293. }
  89294. this._createIndexBuffer();
  89295. };
  89296. Layer.prototype.render = function () {
  89297. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89298. // Check
  89299. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89300. return;
  89301. var engine = this._scene.getEngine();
  89302. this.onBeforeRenderObservable.notifyObservers(this);
  89303. // Render
  89304. engine.enableEffect(currentEffect);
  89305. engine.setState(false);
  89306. // Texture
  89307. currentEffect.setTexture("textureSampler", this.texture);
  89308. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89309. // Color
  89310. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89311. // Scale / offset
  89312. currentEffect.setVector2("offset", this.offset);
  89313. currentEffect.setVector2("scale", this.scale);
  89314. // VBOs
  89315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89316. // Draw order
  89317. if (!this.alphaTest) {
  89318. engine.setAlphaMode(this.alphaBlendingMode);
  89319. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89320. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89321. }
  89322. else {
  89323. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89324. }
  89325. this.onAfterRenderObservable.notifyObservers(this);
  89326. };
  89327. Layer.prototype.dispose = function () {
  89328. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89329. if (vertexBuffer) {
  89330. vertexBuffer.dispose();
  89331. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89332. }
  89333. if (this._indexBuffer) {
  89334. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89335. this._indexBuffer = null;
  89336. }
  89337. if (this.texture) {
  89338. this.texture.dispose();
  89339. this.texture = null;
  89340. }
  89341. // Remove from scene
  89342. var index = this._scene.layers.indexOf(this);
  89343. this._scene.layers.splice(index, 1);
  89344. // Callback
  89345. this.onDisposeObservable.notifyObservers(this);
  89346. this.onDisposeObservable.clear();
  89347. this.onAfterRenderObservable.clear();
  89348. this.onBeforeRenderObservable.clear();
  89349. };
  89350. return Layer;
  89351. }());
  89352. BABYLON.Layer = Layer;
  89353. })(BABYLON || (BABYLON = {}));
  89354. //# sourceMappingURL=babylon.layer.js.map
  89355. "use strict";
  89356. var BABYLON;
  89357. (function (BABYLON) {
  89358. var TextureTools = /** @class */ (function () {
  89359. function TextureTools() {
  89360. }
  89361. /**
  89362. * Uses the GPU to create a copy texture rescaled at a given size
  89363. * @param texture Texture to copy from
  89364. * @param width Desired width
  89365. * @param height Desired height
  89366. * @return Generated texture
  89367. */
  89368. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89369. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89370. var scene = texture.getScene();
  89371. var engine = scene.getEngine();
  89372. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89373. rtt.wrapU = texture.wrapU;
  89374. rtt.wrapV = texture.wrapV;
  89375. rtt.uOffset = texture.uOffset;
  89376. rtt.vOffset = texture.vOffset;
  89377. rtt.uScale = texture.uScale;
  89378. rtt.vScale = texture.vScale;
  89379. rtt.uAng = texture.uAng;
  89380. rtt.vAng = texture.vAng;
  89381. rtt.wAng = texture.wAng;
  89382. rtt.coordinatesIndex = texture.coordinatesIndex;
  89383. rtt.level = texture.level;
  89384. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89385. rtt._texture.isReady = false;
  89386. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89387. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89388. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89389. passPostProcess.getEffect().executeWhenCompiled(function () {
  89390. passPostProcess.onApply = function (effect) {
  89391. effect.setTexture("textureSampler", texture);
  89392. };
  89393. var internalTexture = rtt.getInternalTexture();
  89394. if (internalTexture) {
  89395. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89396. engine.unBindFramebuffer(internalTexture);
  89397. rtt.disposeFramebufferObjects();
  89398. passPostProcess.dispose();
  89399. internalTexture.isReady = true;
  89400. }
  89401. });
  89402. return rtt;
  89403. };
  89404. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89405. if (!scene._environmentBRDFTexture) {
  89406. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89407. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89408. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89409. scene._environmentBRDFTexture = texture;
  89410. }
  89411. return scene._environmentBRDFTexture;
  89412. };
  89413. 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=";
  89414. return TextureTools;
  89415. }());
  89416. BABYLON.TextureTools = TextureTools;
  89417. })(BABYLON || (BABYLON = {}));
  89418. //# sourceMappingURL=babylon.textureTools.js.map
  89419. "use strict";
  89420. var BABYLON;
  89421. (function (BABYLON) {
  89422. var FramingBehavior = /** @class */ (function () {
  89423. function FramingBehavior() {
  89424. this._mode = FramingBehavior.FitFrustumSidesMode;
  89425. this._radiusScale = 1.0;
  89426. this._positionScale = 0.5;
  89427. this._defaultElevation = 0.3;
  89428. this._elevationReturnTime = 1500;
  89429. this._elevationReturnWaitTime = 1000;
  89430. this._zoomStopsAnimation = false;
  89431. this._framingTime = 1500;
  89432. this._isPointerDown = false;
  89433. this._lastInteractionTime = -Infinity;
  89434. // Framing control
  89435. this._animatables = new Array();
  89436. this._betaIsAnimating = false;
  89437. }
  89438. Object.defineProperty(FramingBehavior.prototype, "name", {
  89439. get: function () {
  89440. return "Framing";
  89441. },
  89442. enumerable: true,
  89443. configurable: true
  89444. });
  89445. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89446. /**
  89447. * Gets current mode used by the behavior.
  89448. */
  89449. get: function () {
  89450. return this._mode;
  89451. },
  89452. /**
  89453. * Sets the current mode used by the behavior
  89454. */
  89455. set: function (mode) {
  89456. this._mode = mode;
  89457. },
  89458. enumerable: true,
  89459. configurable: true
  89460. });
  89461. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89462. /**
  89463. * Gets the scale applied to the radius
  89464. */
  89465. get: function () {
  89466. return this._radiusScale;
  89467. },
  89468. /**
  89469. * Sets the scale applied to the radius (1 by default)
  89470. */
  89471. set: function (radius) {
  89472. this._radiusScale = radius;
  89473. },
  89474. enumerable: true,
  89475. configurable: true
  89476. });
  89477. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89478. /**
  89479. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89480. */
  89481. get: function () {
  89482. return this._positionScale;
  89483. },
  89484. /**
  89485. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89486. */
  89487. set: function (scale) {
  89488. this._positionScale = scale;
  89489. },
  89490. enumerable: true,
  89491. configurable: true
  89492. });
  89493. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89494. /**
  89495. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89496. * behaviour is triggered, in radians.
  89497. */
  89498. get: function () {
  89499. return this._defaultElevation;
  89500. },
  89501. /**
  89502. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89503. * behaviour is triggered, in radians.
  89504. */
  89505. set: function (elevation) {
  89506. this._defaultElevation = elevation;
  89507. },
  89508. enumerable: true,
  89509. configurable: true
  89510. });
  89511. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89512. /**
  89513. * Gets the time (in milliseconds) taken to return to the default beta position.
  89514. * Negative value indicates camera should not return to default.
  89515. */
  89516. get: function () {
  89517. return this._elevationReturnTime;
  89518. },
  89519. /**
  89520. * Sets the time (in milliseconds) taken to return to the default beta position.
  89521. * Negative value indicates camera should not return to default.
  89522. */
  89523. set: function (speed) {
  89524. this._elevationReturnTime = speed;
  89525. },
  89526. enumerable: true,
  89527. configurable: true
  89528. });
  89529. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89530. /**
  89531. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89532. */
  89533. get: function () {
  89534. return this._elevationReturnWaitTime;
  89535. },
  89536. /**
  89537. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89538. */
  89539. set: function (time) {
  89540. this._elevationReturnWaitTime = time;
  89541. },
  89542. enumerable: true,
  89543. configurable: true
  89544. });
  89545. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89546. /**
  89547. * Gets the flag that indicates if user zooming should stop animation.
  89548. */
  89549. get: function () {
  89550. return this._zoomStopsAnimation;
  89551. },
  89552. /**
  89553. * Sets the flag that indicates if user zooming should stop animation.
  89554. */
  89555. set: function (flag) {
  89556. this._zoomStopsAnimation = flag;
  89557. },
  89558. enumerable: true,
  89559. configurable: true
  89560. });
  89561. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89562. /**
  89563. * Gets the transition time when framing the mesh, in milliseconds
  89564. */
  89565. get: function () {
  89566. return this._framingTime;
  89567. },
  89568. /**
  89569. * Sets the transition time when framing the mesh, in milliseconds
  89570. */
  89571. set: function (time) {
  89572. this._framingTime = time;
  89573. },
  89574. enumerable: true,
  89575. configurable: true
  89576. });
  89577. FramingBehavior.prototype.init = function () {
  89578. // Do notihng
  89579. };
  89580. FramingBehavior.prototype.attach = function (camera) {
  89581. var _this = this;
  89582. this._attachedCamera = camera;
  89583. var scene = this._attachedCamera.getScene();
  89584. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89585. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89586. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89587. _this._isPointerDown = true;
  89588. return;
  89589. }
  89590. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89591. _this._isPointerDown = false;
  89592. }
  89593. });
  89594. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89595. if (mesh) {
  89596. _this.zoomOnMesh(mesh);
  89597. }
  89598. });
  89599. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89600. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89601. _this._applyUserInteraction();
  89602. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89603. // back to the default position after a given timeout
  89604. _this._maintainCameraAboveGround();
  89605. });
  89606. };
  89607. FramingBehavior.prototype.detach = function () {
  89608. if (!this._attachedCamera) {
  89609. return;
  89610. }
  89611. var scene = this._attachedCamera.getScene();
  89612. if (this._onPrePointerObservableObserver) {
  89613. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89614. }
  89615. if (this._onAfterCheckInputsObserver) {
  89616. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89617. }
  89618. if (this._onMeshTargetChangedObserver) {
  89619. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89620. }
  89621. this._attachedCamera = null;
  89622. };
  89623. /**
  89624. * Targets the given mesh and updates zoom level accordingly.
  89625. * @param mesh The mesh to target.
  89626. * @param radius Optional. If a cached radius position already exists, overrides default.
  89627. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89628. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89629. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89630. */
  89631. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89632. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89633. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89634. mesh.computeWorldMatrix(true);
  89635. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89636. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89637. };
  89638. /**
  89639. * Targets the given mesh with its children and updates zoom level accordingly.
  89640. * @param mesh The mesh to target.
  89641. * @param radius Optional. If a cached radius position already exists, overrides default.
  89642. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89643. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89644. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89645. */
  89646. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89647. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89648. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89649. mesh.computeWorldMatrix(true);
  89650. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89651. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89652. };
  89653. /**
  89654. * Targets the given meshes with their children and updates zoom level accordingly.
  89655. * @param meshes The mesh to target.
  89656. * @param radius Optional. If a cached radius position already exists, overrides default.
  89657. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89658. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89659. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89660. */
  89661. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89662. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89663. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89664. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89665. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89666. for (var i = 0; i < meshes.length; i++) {
  89667. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89668. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89669. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89670. }
  89671. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89672. };
  89673. /**
  89674. * Targets the given mesh and updates zoom level accordingly.
  89675. * @param mesh The mesh to target.
  89676. * @param radius Optional. If a cached radius position already exists, overrides default.
  89677. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89678. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89679. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89680. */
  89681. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89682. var _this = this;
  89683. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89684. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89685. var zoomTarget;
  89686. if (!this._attachedCamera) {
  89687. return;
  89688. }
  89689. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89690. var bottom = minimumWorld.y;
  89691. var top = maximumWorld.y;
  89692. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89693. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89694. if (focusOnOriginXZ) {
  89695. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89696. }
  89697. else {
  89698. var centerWorld = minimumWorld.add(radiusWorld);
  89699. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89700. }
  89701. if (!this._vectorTransition) {
  89702. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89703. }
  89704. this._betaIsAnimating = true;
  89705. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89706. if (animatable) {
  89707. this._animatables.push(animatable);
  89708. }
  89709. // sets the radius and lower radius bounds
  89710. // Small delta ensures camera is not always at lower zoom limit.
  89711. var radius = 0;
  89712. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89713. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89714. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89715. radius = position;
  89716. }
  89717. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89718. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89719. if (this._attachedCamera.lowerRadiusLimit === null) {
  89720. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89721. }
  89722. }
  89723. // Set sensibilities
  89724. var extend = maximumWorld.subtract(minimumWorld).length();
  89725. this._attachedCamera.panningSensibility = 5000 / extend;
  89726. this._attachedCamera.wheelPrecision = 100 / radius;
  89727. // transition to new radius
  89728. if (!this._radiusTransition) {
  89729. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89730. }
  89731. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89732. _this.stopAllAnimations();
  89733. if (onAnimationEnd) {
  89734. onAnimationEnd();
  89735. }
  89736. if (_this._attachedCamera) {
  89737. _this._attachedCamera.storeState();
  89738. }
  89739. });
  89740. if (animatable) {
  89741. this._animatables.push(animatable);
  89742. }
  89743. };
  89744. /**
  89745. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89746. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89747. * frustum width.
  89748. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89749. * to fully enclose the mesh in the viewing frustum.
  89750. */
  89751. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89752. var size = maximumWorld.subtract(minimumWorld);
  89753. var boxVectorGlobalDiagonal = size.length();
  89754. var frustumSlope = this._getFrustumSlope();
  89755. // Formula for setting distance
  89756. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89757. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89758. // Horizon distance
  89759. var radius = radiusWithoutFraming * this._radiusScale;
  89760. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89761. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89762. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89763. var camera = this._attachedCamera;
  89764. if (!camera) {
  89765. return 0;
  89766. }
  89767. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89768. // Don't exceed the requested limit
  89769. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89770. }
  89771. // Don't exceed the upper radius limit
  89772. if (camera.upperRadiusLimit) {
  89773. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89774. }
  89775. return distance;
  89776. };
  89777. /**
  89778. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89779. * is automatically returned to its default position (expected to be above ground plane).
  89780. */
  89781. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89782. var _this = this;
  89783. if (this._elevationReturnTime < 0) {
  89784. return;
  89785. }
  89786. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89787. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89788. var limitBeta = Math.PI * 0.5;
  89789. // Bring the camera back up if below the ground plane
  89790. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89791. this._betaIsAnimating = true;
  89792. //Transition to new position
  89793. this.stopAllAnimations();
  89794. if (!this._betaTransition) {
  89795. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89796. }
  89797. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89798. _this._clearAnimationLocks();
  89799. _this.stopAllAnimations();
  89800. });
  89801. if (animatabe) {
  89802. this._animatables.push(animatabe);
  89803. }
  89804. }
  89805. };
  89806. /**
  89807. * Returns the frustum slope based on the canvas ratio and camera FOV
  89808. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89809. */
  89810. FramingBehavior.prototype._getFrustumSlope = function () {
  89811. // Calculate the viewport ratio
  89812. // Aspect Ratio is Height/Width.
  89813. var camera = this._attachedCamera;
  89814. if (!camera) {
  89815. return BABYLON.Vector2.Zero();
  89816. }
  89817. var engine = camera.getScene().getEngine();
  89818. var aspectRatio = engine.getAspectRatio(camera);
  89819. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89820. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89821. var frustumSlopeY = Math.tan(camera.fov / 2);
  89822. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89823. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89824. // along the forward vector.
  89825. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89826. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89827. };
  89828. /**
  89829. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89830. */
  89831. FramingBehavior.prototype._clearAnimationLocks = function () {
  89832. this._betaIsAnimating = false;
  89833. };
  89834. /**
  89835. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89836. */
  89837. FramingBehavior.prototype._applyUserInteraction = function () {
  89838. if (this.isUserIsMoving) {
  89839. this._lastInteractionTime = BABYLON.Tools.Now;
  89840. this.stopAllAnimations();
  89841. this._clearAnimationLocks();
  89842. }
  89843. };
  89844. /**
  89845. * Stops and removes all animations that have been applied to the camera
  89846. */
  89847. FramingBehavior.prototype.stopAllAnimations = function () {
  89848. if (this._attachedCamera) {
  89849. this._attachedCamera.animations = [];
  89850. }
  89851. while (this._animatables.length) {
  89852. if (this._animatables[0]) {
  89853. this._animatables[0].onAnimationEnd = null;
  89854. this._animatables[0].stop();
  89855. }
  89856. this._animatables.shift();
  89857. }
  89858. };
  89859. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89860. /**
  89861. * Gets a value indicating if the user is moving the camera
  89862. */
  89863. get: function () {
  89864. if (!this._attachedCamera) {
  89865. return false;
  89866. }
  89867. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89868. this._attachedCamera.inertialBetaOffset !== 0 ||
  89869. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89870. this._attachedCamera.inertialPanningX !== 0 ||
  89871. this._attachedCamera.inertialPanningY !== 0 ||
  89872. this._isPointerDown;
  89873. },
  89874. enumerable: true,
  89875. configurable: true
  89876. });
  89877. /**
  89878. * The easing function used by animations
  89879. */
  89880. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89881. /**
  89882. * The easing mode used by animations
  89883. */
  89884. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89885. // Statics
  89886. /**
  89887. * The camera can move all the way towards the mesh.
  89888. */
  89889. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89890. /**
  89891. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89892. */
  89893. FramingBehavior.FitFrustumSidesMode = 1;
  89894. return FramingBehavior;
  89895. }());
  89896. BABYLON.FramingBehavior = FramingBehavior;
  89897. })(BABYLON || (BABYLON = {}));
  89898. //# sourceMappingURL=babylon.framingBehavior.js.map
  89899. "use strict";
  89900. var BABYLON;
  89901. (function (BABYLON) {
  89902. /**
  89903. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89904. */
  89905. var BouncingBehavior = /** @class */ (function () {
  89906. function BouncingBehavior() {
  89907. /**
  89908. * The duration of the animation, in milliseconds
  89909. */
  89910. this.transitionDuration = 450;
  89911. /**
  89912. * Length of the distance animated by the transition when lower radius is reached
  89913. */
  89914. this.lowerRadiusTransitionRange = 2;
  89915. /**
  89916. * Length of the distance animated by the transition when upper radius is reached
  89917. */
  89918. this.upperRadiusTransitionRange = -2;
  89919. this._autoTransitionRange = false;
  89920. // Animations
  89921. this._radiusIsAnimating = false;
  89922. this._radiusBounceTransition = null;
  89923. this._animatables = new Array();
  89924. }
  89925. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89926. get: function () {
  89927. return "Bouncing";
  89928. },
  89929. enumerable: true,
  89930. configurable: true
  89931. });
  89932. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89933. /**
  89934. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89935. */
  89936. get: function () {
  89937. return this._autoTransitionRange;
  89938. },
  89939. /**
  89940. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89941. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89942. */
  89943. set: function (value) {
  89944. var _this = this;
  89945. if (this._autoTransitionRange === value) {
  89946. return;
  89947. }
  89948. this._autoTransitionRange = value;
  89949. var camera = this._attachedCamera;
  89950. if (!camera) {
  89951. return;
  89952. }
  89953. if (value) {
  89954. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89955. if (!mesh) {
  89956. return;
  89957. }
  89958. mesh.computeWorldMatrix(true);
  89959. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89960. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89961. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89962. });
  89963. }
  89964. else if (this._onMeshTargetChangedObserver) {
  89965. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89966. }
  89967. },
  89968. enumerable: true,
  89969. configurable: true
  89970. });
  89971. BouncingBehavior.prototype.init = function () {
  89972. // Do notihng
  89973. };
  89974. BouncingBehavior.prototype.attach = function (camera) {
  89975. var _this = this;
  89976. this._attachedCamera = camera;
  89977. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89978. if (!_this._attachedCamera) {
  89979. return;
  89980. }
  89981. // Add the bounce animation to the lower radius limit
  89982. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89983. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89984. }
  89985. // Add the bounce animation to the upper radius limit
  89986. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89987. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89988. }
  89989. });
  89990. };
  89991. BouncingBehavior.prototype.detach = function () {
  89992. if (!this._attachedCamera) {
  89993. return;
  89994. }
  89995. if (this._onAfterCheckInputsObserver) {
  89996. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89997. }
  89998. if (this._onMeshTargetChangedObserver) {
  89999. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  90000. }
  90001. this._attachedCamera = null;
  90002. };
  90003. /**
  90004. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  90005. * @param radiusLimit The limit to check against.
  90006. * @return Bool to indicate if at limit.
  90007. */
  90008. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  90009. if (!this._attachedCamera) {
  90010. return false;
  90011. }
  90012. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  90013. return true;
  90014. }
  90015. return false;
  90016. };
  90017. /**
  90018. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  90019. * @param radiusDelta The delta by which to animate to. Can be negative.
  90020. */
  90021. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  90022. var _this = this;
  90023. if (!this._attachedCamera) {
  90024. return;
  90025. }
  90026. if (!this._radiusBounceTransition) {
  90027. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  90028. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  90029. }
  90030. // Prevent zoom until bounce has completed
  90031. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  90032. this._attachedCamera.wheelPrecision = Infinity;
  90033. this._attachedCamera.inertialRadiusOffset = 0;
  90034. // Animate to the radius limit
  90035. this.stopAllAnimations();
  90036. this._radiusIsAnimating = true;
  90037. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  90038. if (animatable) {
  90039. this._animatables.push(animatable);
  90040. }
  90041. };
  90042. /**
  90043. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  90044. */
  90045. BouncingBehavior.prototype._clearAnimationLocks = function () {
  90046. this._radiusIsAnimating = false;
  90047. if (this._attachedCamera) {
  90048. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  90049. }
  90050. };
  90051. /**
  90052. * Stops and removes all animations that have been applied to the camera
  90053. */
  90054. BouncingBehavior.prototype.stopAllAnimations = function () {
  90055. if (this._attachedCamera) {
  90056. this._attachedCamera.animations = [];
  90057. }
  90058. while (this._animatables.length) {
  90059. this._animatables[0].onAnimationEnd = null;
  90060. this._animatables[0].stop();
  90061. this._animatables.shift();
  90062. }
  90063. };
  90064. /**
  90065. * The easing function used by animations
  90066. */
  90067. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  90068. /**
  90069. * The easing mode used by animations
  90070. */
  90071. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  90072. return BouncingBehavior;
  90073. }());
  90074. BABYLON.BouncingBehavior = BouncingBehavior;
  90075. })(BABYLON || (BABYLON = {}));
  90076. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  90077. "use strict";
  90078. var BABYLON;
  90079. (function (BABYLON) {
  90080. var AutoRotationBehavior = /** @class */ (function () {
  90081. function AutoRotationBehavior() {
  90082. this._zoomStopsAnimation = false;
  90083. this._idleRotationSpeed = 0.05;
  90084. this._idleRotationWaitTime = 2000;
  90085. this._idleRotationSpinupTime = 2000;
  90086. this._isPointerDown = false;
  90087. this._lastFrameTime = null;
  90088. this._lastInteractionTime = -Infinity;
  90089. this._cameraRotationSpeed = 0;
  90090. this._lastFrameRadius = 0;
  90091. }
  90092. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  90093. get: function () {
  90094. return "AutoRotation";
  90095. },
  90096. enumerable: true,
  90097. configurable: true
  90098. });
  90099. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  90100. /**
  90101. * Gets the flag that indicates if user zooming should stop animation.
  90102. */
  90103. get: function () {
  90104. return this._zoomStopsAnimation;
  90105. },
  90106. /**
  90107. * Sets the flag that indicates if user zooming should stop animation.
  90108. */
  90109. set: function (flag) {
  90110. this._zoomStopsAnimation = flag;
  90111. },
  90112. enumerable: true,
  90113. configurable: true
  90114. });
  90115. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  90116. /**
  90117. * Gets the default speed at which the camera rotates around the model.
  90118. */
  90119. get: function () {
  90120. return this._idleRotationSpeed;
  90121. },
  90122. /**
  90123. * Sets the default speed at which the camera rotates around the model.
  90124. */
  90125. set: function (speed) {
  90126. this._idleRotationSpeed = speed;
  90127. },
  90128. enumerable: true,
  90129. configurable: true
  90130. });
  90131. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  90132. /**
  90133. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  90134. */
  90135. get: function () {
  90136. return this._idleRotationWaitTime;
  90137. },
  90138. /**
  90139. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  90140. */
  90141. set: function (time) {
  90142. this._idleRotationWaitTime = time;
  90143. },
  90144. enumerable: true,
  90145. configurable: true
  90146. });
  90147. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  90148. /**
  90149. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90150. */
  90151. get: function () {
  90152. return this._idleRotationSpinupTime;
  90153. },
  90154. /**
  90155. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90156. */
  90157. set: function (time) {
  90158. this._idleRotationSpinupTime = time;
  90159. },
  90160. enumerable: true,
  90161. configurable: true
  90162. });
  90163. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  90164. /**
  90165. * Gets a value indicating if the camera is currently rotating because of this behavior
  90166. */
  90167. get: function () {
  90168. return Math.abs(this._cameraRotationSpeed) > 0;
  90169. },
  90170. enumerable: true,
  90171. configurable: true
  90172. });
  90173. AutoRotationBehavior.prototype.init = function () {
  90174. // Do notihng
  90175. };
  90176. AutoRotationBehavior.prototype.attach = function (camera) {
  90177. var _this = this;
  90178. this._attachedCamera = camera;
  90179. var scene = this._attachedCamera.getScene();
  90180. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  90181. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90182. _this._isPointerDown = true;
  90183. return;
  90184. }
  90185. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  90186. _this._isPointerDown = false;
  90187. }
  90188. });
  90189. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  90190. var now = BABYLON.Tools.Now;
  90191. var dt = 0;
  90192. if (_this._lastFrameTime != null) {
  90193. dt = now - _this._lastFrameTime;
  90194. }
  90195. _this._lastFrameTime = now;
  90196. // Stop the animation if there is user interaction and the animation should stop for this interaction
  90197. _this._applyUserInteraction();
  90198. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  90199. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  90200. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  90201. // Step camera rotation by rotation speed
  90202. if (_this._attachedCamera) {
  90203. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  90204. }
  90205. });
  90206. };
  90207. AutoRotationBehavior.prototype.detach = function () {
  90208. if (!this._attachedCamera) {
  90209. return;
  90210. }
  90211. var scene = this._attachedCamera.getScene();
  90212. if (this._onPrePointerObservableObserver) {
  90213. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  90214. }
  90215. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90216. this._attachedCamera = null;
  90217. };
  90218. /**
  90219. * Returns true if user is scrolling.
  90220. * @return true if user is scrolling.
  90221. */
  90222. AutoRotationBehavior.prototype._userIsZooming = function () {
  90223. if (!this._attachedCamera) {
  90224. return false;
  90225. }
  90226. return this._attachedCamera.inertialRadiusOffset !== 0;
  90227. };
  90228. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  90229. if (!this._attachedCamera) {
  90230. return false;
  90231. }
  90232. var zoomHasHitLimit = false;
  90233. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  90234. zoomHasHitLimit = true;
  90235. }
  90236. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  90237. this._lastFrameRadius = this._attachedCamera.radius;
  90238. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  90239. };
  90240. /**
  90241. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90242. */
  90243. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  90244. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  90245. this._lastInteractionTime = BABYLON.Tools.Now;
  90246. }
  90247. };
  90248. // Tools
  90249. AutoRotationBehavior.prototype._userIsMoving = function () {
  90250. if (!this._attachedCamera) {
  90251. return false;
  90252. }
  90253. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90254. this._attachedCamera.inertialBetaOffset !== 0 ||
  90255. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90256. this._attachedCamera.inertialPanningX !== 0 ||
  90257. this._attachedCamera.inertialPanningY !== 0 ||
  90258. this._isPointerDown;
  90259. };
  90260. return AutoRotationBehavior;
  90261. }());
  90262. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90263. })(BABYLON || (BABYLON = {}));
  90264. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90265. "use strict";
  90266. var BABYLON;
  90267. (function (BABYLON) {
  90268. var NullEngineOptions = /** @class */ (function () {
  90269. function NullEngineOptions() {
  90270. this.renderWidth = 512;
  90271. this.renderHeight = 256;
  90272. this.textureSize = 512;
  90273. this.deterministicLockstep = false;
  90274. this.lockstepMaxSteps = 4;
  90275. }
  90276. return NullEngineOptions;
  90277. }());
  90278. BABYLON.NullEngineOptions = NullEngineOptions;
  90279. /**
  90280. * The null engine class provides support for headless version of babylon.js.
  90281. * This can be used in server side scenario or for testing purposes
  90282. */
  90283. var NullEngine = /** @class */ (function (_super) {
  90284. __extends(NullEngine, _super);
  90285. function NullEngine(options) {
  90286. if (options === void 0) { options = new NullEngineOptions(); }
  90287. var _this = _super.call(this, null) || this;
  90288. if (options.deterministicLockstep === undefined) {
  90289. options.deterministicLockstep = false;
  90290. }
  90291. if (options.lockstepMaxSteps === undefined) {
  90292. options.lockstepMaxSteps = 4;
  90293. }
  90294. _this._options = options;
  90295. // Init caps
  90296. // We consider we are on a webgl1 capable device
  90297. _this._caps = new BABYLON.EngineCapabilities();
  90298. _this._caps.maxTexturesImageUnits = 16;
  90299. _this._caps.maxVertexTextureImageUnits = 16;
  90300. _this._caps.maxTextureSize = 512;
  90301. _this._caps.maxCubemapTextureSize = 512;
  90302. _this._caps.maxRenderTextureSize = 512;
  90303. _this._caps.maxVertexAttribs = 16;
  90304. _this._caps.maxVaryingVectors = 16;
  90305. _this._caps.maxFragmentUniformVectors = 16;
  90306. _this._caps.maxVertexUniformVectors = 16;
  90307. // Extensions
  90308. _this._caps.standardDerivatives = false;
  90309. _this._caps.astc = null;
  90310. _this._caps.s3tc = null;
  90311. _this._caps.pvrtc = null;
  90312. _this._caps.etc1 = null;
  90313. _this._caps.etc2 = null;
  90314. _this._caps.textureAnisotropicFilterExtension = null;
  90315. _this._caps.maxAnisotropy = 0;
  90316. _this._caps.uintIndices = false;
  90317. _this._caps.fragmentDepthSupported = false;
  90318. _this._caps.highPrecisionShaderSupported = true;
  90319. _this._caps.colorBufferFloat = false;
  90320. _this._caps.textureFloat = false;
  90321. _this._caps.textureFloatLinearFiltering = false;
  90322. _this._caps.textureFloatRender = false;
  90323. _this._caps.textureHalfFloat = false;
  90324. _this._caps.textureHalfFloatLinearFiltering = false;
  90325. _this._caps.textureHalfFloatRender = false;
  90326. _this._caps.textureLOD = false;
  90327. _this._caps.drawBuffersExtension = false;
  90328. _this._caps.depthTextureExtension = false;
  90329. _this._caps.vertexArrayObject = false;
  90330. _this._caps.instancedArrays = false;
  90331. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90332. // Wrappers
  90333. if (typeof URL === "undefined") {
  90334. URL = {
  90335. createObjectURL: function () { },
  90336. revokeObjectURL: function () { }
  90337. };
  90338. }
  90339. if (typeof Blob === "undefined") {
  90340. Blob = function () { };
  90341. }
  90342. return _this;
  90343. }
  90344. NullEngine.prototype.isDeterministicLockStep = function () {
  90345. return this._options.deterministicLockstep;
  90346. };
  90347. NullEngine.prototype.getLockstepMaxSteps = function () {
  90348. return this._options.lockstepMaxSteps;
  90349. };
  90350. NullEngine.prototype.getHardwareScalingLevel = function () {
  90351. return 1.0;
  90352. };
  90353. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90354. return {
  90355. capacity: 0,
  90356. references: 1,
  90357. is32Bits: false
  90358. };
  90359. };
  90360. NullEngine.prototype.createIndexBuffer = function (indices) {
  90361. return {
  90362. capacity: 0,
  90363. references: 1,
  90364. is32Bits: false
  90365. };
  90366. };
  90367. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90368. if (stencil === void 0) { stencil = false; }
  90369. };
  90370. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90371. if (useScreen === void 0) { useScreen = false; }
  90372. if (!useScreen && this._currentRenderTarget) {
  90373. return this._currentRenderTarget.width;
  90374. }
  90375. return this._options.renderWidth;
  90376. };
  90377. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90378. if (useScreen === void 0) { useScreen = false; }
  90379. if (!useScreen && this._currentRenderTarget) {
  90380. return this._currentRenderTarget.height;
  90381. }
  90382. return this._options.renderHeight;
  90383. };
  90384. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90385. this._cachedViewport = viewport;
  90386. };
  90387. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90388. return {
  90389. transformFeedback: null,
  90390. __SPECTOR_rebuildProgram: null
  90391. };
  90392. };
  90393. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90394. return [];
  90395. };
  90396. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90397. return [];
  90398. };
  90399. NullEngine.prototype.bindSamplers = function (effect) {
  90400. this._currentEffect = null;
  90401. };
  90402. NullEngine.prototype.enableEffect = function (effect) {
  90403. this._currentEffect = effect;
  90404. if (effect.onBind) {
  90405. effect.onBind(effect);
  90406. }
  90407. effect.onBindObservable.notifyObservers(effect);
  90408. };
  90409. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90410. if (zOffset === void 0) { zOffset = 0; }
  90411. if (reverseSide === void 0) { reverseSide = false; }
  90412. };
  90413. NullEngine.prototype.setIntArray = function (uniform, array) {
  90414. };
  90415. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90416. };
  90417. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90418. };
  90419. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90420. };
  90421. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90422. };
  90423. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90424. };
  90425. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90426. };
  90427. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90428. };
  90429. NullEngine.prototype.setArray = function (uniform, array) {
  90430. };
  90431. NullEngine.prototype.setArray2 = function (uniform, array) {
  90432. };
  90433. NullEngine.prototype.setArray3 = function (uniform, array) {
  90434. };
  90435. NullEngine.prototype.setArray4 = function (uniform, array) {
  90436. };
  90437. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90438. };
  90439. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90440. };
  90441. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90442. };
  90443. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90444. };
  90445. NullEngine.prototype.setFloat = function (uniform, value) {
  90446. };
  90447. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90448. };
  90449. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90450. };
  90451. NullEngine.prototype.setBool = function (uniform, bool) {
  90452. };
  90453. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90454. };
  90455. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90456. };
  90457. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90458. };
  90459. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90460. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90461. if (this._alphaMode === mode) {
  90462. return;
  90463. }
  90464. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90465. if (!noDepthWriteChange) {
  90466. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90467. }
  90468. this._alphaMode = mode;
  90469. };
  90470. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90471. };
  90472. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90473. if (this.preventCacheWipeBetweenFrames) {
  90474. return;
  90475. }
  90476. this.resetTextureCache();
  90477. this._currentEffect = null;
  90478. if (bruteForce) {
  90479. this._currentProgram = null;
  90480. this._stencilState.reset();
  90481. this._depthCullingState.reset();
  90482. this._alphaState.reset();
  90483. }
  90484. this._cachedVertexBuffers = null;
  90485. this._cachedIndexBuffer = null;
  90486. this._cachedEffectForVertexBuffers = null;
  90487. };
  90488. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90489. };
  90490. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90491. };
  90492. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90493. };
  90494. NullEngine.prototype._createTexture = function () {
  90495. return {};
  90496. };
  90497. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90499. if (onLoad === void 0) { onLoad = null; }
  90500. if (onError === void 0) { onError = null; }
  90501. if (buffer === void 0) { buffer = null; }
  90502. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90503. var url = String(urlArg);
  90504. texture.url = url;
  90505. texture.generateMipMaps = !noMipmap;
  90506. texture.samplingMode = samplingMode;
  90507. texture.invertY = invertY;
  90508. texture.baseWidth = this._options.textureSize;
  90509. texture.baseHeight = this._options.textureSize;
  90510. texture.width = this._options.textureSize;
  90511. texture.height = this._options.textureSize;
  90512. if (format) {
  90513. texture.format = format;
  90514. }
  90515. texture.isReady = true;
  90516. if (onLoad) {
  90517. onLoad();
  90518. }
  90519. return texture;
  90520. };
  90521. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90522. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90523. if (options !== undefined && typeof options === "object") {
  90524. fullOptions.generateMipMaps = options.generateMipMaps;
  90525. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90526. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90527. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90528. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90529. }
  90530. else {
  90531. fullOptions.generateMipMaps = options;
  90532. fullOptions.generateDepthBuffer = true;
  90533. fullOptions.generateStencilBuffer = false;
  90534. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90535. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90536. }
  90537. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90538. var width = size.width || size;
  90539. var height = size.height || size;
  90540. texture._depthStencilBuffer = {};
  90541. texture._framebuffer = {};
  90542. texture.baseWidth = width;
  90543. texture.baseHeight = height;
  90544. texture.width = width;
  90545. texture.height = height;
  90546. texture.isReady = true;
  90547. texture.samples = 1;
  90548. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90549. texture.samplingMode = fullOptions.samplingMode;
  90550. texture.type = fullOptions.type;
  90551. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90552. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90553. return texture;
  90554. };
  90555. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90556. texture.samplingMode = samplingMode;
  90557. };
  90558. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90559. if (this._currentRenderTarget) {
  90560. this.unBindFramebuffer(this._currentRenderTarget);
  90561. }
  90562. this._currentRenderTarget = texture;
  90563. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90564. if (this._cachedViewport && !forceFullscreenViewport) {
  90565. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90566. }
  90567. };
  90568. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90569. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90570. this._currentRenderTarget = null;
  90571. if (onBeforeUnbind) {
  90572. if (texture._MSAAFramebuffer) {
  90573. this._currentFramebuffer = texture._framebuffer;
  90574. }
  90575. onBeforeUnbind();
  90576. }
  90577. this._currentFramebuffer = null;
  90578. };
  90579. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90580. var vbo = {
  90581. capacity: 1,
  90582. references: 1,
  90583. is32Bits: false
  90584. };
  90585. return vbo;
  90586. };
  90587. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90588. if (offset === void 0) { offset = 0; }
  90589. };
  90590. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90591. };
  90592. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90593. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90594. this._boundTexturesCache[this._activeChannel] = texture;
  90595. }
  90596. };
  90597. NullEngine.prototype._bindTexture = function (channel, texture) {
  90598. if (channel < 0) {
  90599. return;
  90600. }
  90601. this._bindTextureDirectly(0, texture);
  90602. };
  90603. NullEngine.prototype._releaseBuffer = function (buffer) {
  90604. buffer.references--;
  90605. if (buffer.references === 0) {
  90606. return true;
  90607. }
  90608. return false;
  90609. };
  90610. return NullEngine;
  90611. }(BABYLON.Engine));
  90612. BABYLON.NullEngine = NullEngine;
  90613. })(BABYLON || (BABYLON = {}));
  90614. //# sourceMappingURL=babylon.nullEngine.js.map
  90615. "use strict";
  90616. var BABYLON;
  90617. (function (BABYLON) {
  90618. /**
  90619. * This class can be used to get instrumentation data from a Babylon engine
  90620. */
  90621. var EngineInstrumentation = /** @class */ (function () {
  90622. function EngineInstrumentation(engine) {
  90623. this.engine = engine;
  90624. this._captureGPUFrameTime = false;
  90625. this._gpuFrameTime = new BABYLON.PerfCounter();
  90626. this._captureShaderCompilationTime = false;
  90627. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90628. // Observers
  90629. this._onBeginFrameObserver = null;
  90630. this._onEndFrameObserver = null;
  90631. this._onBeforeShaderCompilationObserver = null;
  90632. this._onAfterShaderCompilationObserver = null;
  90633. }
  90634. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90635. // Properties
  90636. /**
  90637. * Gets the perf counter used for GPU frame time
  90638. */
  90639. get: function () {
  90640. return this._gpuFrameTime;
  90641. },
  90642. enumerable: true,
  90643. configurable: true
  90644. });
  90645. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90646. /**
  90647. * Gets the GPU frame time capture status
  90648. */
  90649. get: function () {
  90650. return this._captureGPUFrameTime;
  90651. },
  90652. /**
  90653. * Enable or disable the GPU frame time capture
  90654. */
  90655. set: function (value) {
  90656. var _this = this;
  90657. if (value === this._captureGPUFrameTime) {
  90658. return;
  90659. }
  90660. this._captureGPUFrameTime = value;
  90661. if (value) {
  90662. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90663. if (!_this._gpuFrameTimeToken) {
  90664. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90665. }
  90666. });
  90667. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90668. if (!_this._gpuFrameTimeToken) {
  90669. return;
  90670. }
  90671. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90672. if (time > -1) {
  90673. _this._gpuFrameTimeToken = null;
  90674. _this._gpuFrameTime.fetchNewFrame();
  90675. _this._gpuFrameTime.addCount(time, true);
  90676. }
  90677. });
  90678. }
  90679. else {
  90680. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90681. this._onBeginFrameObserver = null;
  90682. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90683. this._onEndFrameObserver = null;
  90684. }
  90685. },
  90686. enumerable: true,
  90687. configurable: true
  90688. });
  90689. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90690. /**
  90691. * Gets the perf counter used for shader compilation time
  90692. */
  90693. get: function () {
  90694. return this._shaderCompilationTime;
  90695. },
  90696. enumerable: true,
  90697. configurable: true
  90698. });
  90699. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90700. /**
  90701. * Gets the shader compilation time capture status
  90702. */
  90703. get: function () {
  90704. return this._captureShaderCompilationTime;
  90705. },
  90706. /**
  90707. * Enable or disable the shader compilation time capture
  90708. */
  90709. set: function (value) {
  90710. var _this = this;
  90711. if (value === this._captureShaderCompilationTime) {
  90712. return;
  90713. }
  90714. this._captureShaderCompilationTime = value;
  90715. if (value) {
  90716. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90717. _this._shaderCompilationTime.fetchNewFrame();
  90718. _this._shaderCompilationTime.beginMonitoring();
  90719. });
  90720. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90721. _this._shaderCompilationTime.endMonitoring();
  90722. });
  90723. }
  90724. else {
  90725. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90726. this._onBeforeShaderCompilationObserver = null;
  90727. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90728. this._onAfterShaderCompilationObserver = null;
  90729. }
  90730. },
  90731. enumerable: true,
  90732. configurable: true
  90733. });
  90734. EngineInstrumentation.prototype.dispose = function () {
  90735. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90736. this._onBeginFrameObserver = null;
  90737. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90738. this._onEndFrameObserver = null;
  90739. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90740. this._onBeforeShaderCompilationObserver = null;
  90741. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90742. this._onAfterShaderCompilationObserver = null;
  90743. this.engine = null;
  90744. };
  90745. return EngineInstrumentation;
  90746. }());
  90747. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90748. })(BABYLON || (BABYLON = {}));
  90749. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90750. "use strict";
  90751. var BABYLON;
  90752. (function (BABYLON) {
  90753. /**
  90754. * This class can be used to get instrumentation data from a Babylon engine
  90755. */
  90756. var SceneInstrumentation = /** @class */ (function () {
  90757. function SceneInstrumentation(scene) {
  90758. var _this = this;
  90759. this.scene = scene;
  90760. this._captureActiveMeshesEvaluationTime = false;
  90761. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90762. this._captureRenderTargetsRenderTime = false;
  90763. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90764. this._captureFrameTime = false;
  90765. this._frameTime = new BABYLON.PerfCounter();
  90766. this._captureRenderTime = false;
  90767. this._renderTime = new BABYLON.PerfCounter();
  90768. this._captureInterFrameTime = false;
  90769. this._interFrameTime = new BABYLON.PerfCounter();
  90770. this._captureParticlesRenderTime = false;
  90771. this._particlesRenderTime = new BABYLON.PerfCounter();
  90772. this._captureSpritesRenderTime = false;
  90773. this._spritesRenderTime = new BABYLON.PerfCounter();
  90774. this._capturePhysicsTime = false;
  90775. this._physicsTime = new BABYLON.PerfCounter();
  90776. this._captureAnimationsTime = false;
  90777. this._animationsTime = new BABYLON.PerfCounter();
  90778. // Observers
  90779. this._onBeforeActiveMeshesEvaluationObserver = null;
  90780. this._onAfterActiveMeshesEvaluationObserver = null;
  90781. this._onBeforeRenderTargetsRenderObserver = null;
  90782. this._onAfterRenderTargetsRenderObserver = null;
  90783. this._onAfterRenderObserver = null;
  90784. this._onBeforeDrawPhaseObserver = null;
  90785. this._onAfterDrawPhaseObserver = null;
  90786. this._onBeforeAnimationsObserver = null;
  90787. this._onBeforeParticlesRenderingObserver = null;
  90788. this._onAfterParticlesRenderingObserver = null;
  90789. this._onBeforeSpritesRenderingObserver = null;
  90790. this._onAfterSpritesRenderingObserver = null;
  90791. this._onBeforePhysicsObserver = null;
  90792. this._onAfterPhysicsObserver = null;
  90793. this._onAfterAnimationsObserver = null;
  90794. // Before render
  90795. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90796. if (_this._captureActiveMeshesEvaluationTime) {
  90797. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90798. }
  90799. if (_this._captureRenderTargetsRenderTime) {
  90800. _this._renderTargetsRenderTime.fetchNewFrame();
  90801. }
  90802. if (_this._captureFrameTime) {
  90803. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90804. _this._frameTime.beginMonitoring();
  90805. }
  90806. if (_this._captureInterFrameTime) {
  90807. _this._interFrameTime.endMonitoring();
  90808. }
  90809. if (_this._captureParticlesRenderTime) {
  90810. _this._particlesRenderTime.fetchNewFrame();
  90811. }
  90812. if (_this._captureSpritesRenderTime) {
  90813. _this._spritesRenderTime.fetchNewFrame();
  90814. }
  90815. if (_this._captureAnimationsTime) {
  90816. _this._animationsTime.beginMonitoring();
  90817. }
  90818. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90819. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90820. });
  90821. // After render
  90822. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90823. if (_this._captureFrameTime) {
  90824. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90825. _this._frameTime.endMonitoring();
  90826. }
  90827. if (_this._captureRenderTime) {
  90828. _this._renderTime.endMonitoring(false);
  90829. }
  90830. if (_this._captureInterFrameTime) {
  90831. _this._interFrameTime.beginMonitoring();
  90832. }
  90833. });
  90834. }
  90835. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90836. // Properties
  90837. /**
  90838. * Gets the perf counter used for active meshes evaluation time
  90839. */
  90840. get: function () {
  90841. return this._activeMeshesEvaluationTime;
  90842. },
  90843. enumerable: true,
  90844. configurable: true
  90845. });
  90846. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90847. /**
  90848. * Gets the active meshes evaluation time capture status
  90849. */
  90850. get: function () {
  90851. return this._captureActiveMeshesEvaluationTime;
  90852. },
  90853. /**
  90854. * Enable or disable the active meshes evaluation time capture
  90855. */
  90856. set: function (value) {
  90857. var _this = this;
  90858. if (value === this._captureActiveMeshesEvaluationTime) {
  90859. return;
  90860. }
  90861. this._captureActiveMeshesEvaluationTime = value;
  90862. if (value) {
  90863. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90864. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90865. _this._activeMeshesEvaluationTime.beginMonitoring();
  90866. });
  90867. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90868. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90869. _this._activeMeshesEvaluationTime.endMonitoring();
  90870. });
  90871. }
  90872. else {
  90873. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90874. this._onBeforeActiveMeshesEvaluationObserver = null;
  90875. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90876. this._onAfterActiveMeshesEvaluationObserver = null;
  90877. }
  90878. },
  90879. enumerable: true,
  90880. configurable: true
  90881. });
  90882. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90883. /**
  90884. * Gets the perf counter used for render targets render time
  90885. */
  90886. get: function () {
  90887. return this._renderTargetsRenderTime;
  90888. },
  90889. enumerable: true,
  90890. configurable: true
  90891. });
  90892. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90893. /**
  90894. * Gets the render targets render time capture status
  90895. */
  90896. get: function () {
  90897. return this._captureRenderTargetsRenderTime;
  90898. },
  90899. /**
  90900. * Enable or disable the render targets render time capture
  90901. */
  90902. set: function (value) {
  90903. var _this = this;
  90904. if (value === this._captureRenderTargetsRenderTime) {
  90905. return;
  90906. }
  90907. this._captureRenderTargetsRenderTime = value;
  90908. if (value) {
  90909. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90910. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90911. _this._renderTargetsRenderTime.beginMonitoring();
  90912. });
  90913. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90914. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90915. _this._renderTargetsRenderTime.endMonitoring(false);
  90916. });
  90917. }
  90918. else {
  90919. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90920. this._onBeforeRenderTargetsRenderObserver = null;
  90921. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90922. this._onAfterRenderTargetsRenderObserver = null;
  90923. }
  90924. },
  90925. enumerable: true,
  90926. configurable: true
  90927. });
  90928. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90929. /**
  90930. * Gets the perf counter used for particles render time
  90931. */
  90932. get: function () {
  90933. return this._particlesRenderTime;
  90934. },
  90935. enumerable: true,
  90936. configurable: true
  90937. });
  90938. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90939. /**
  90940. * Gets the particles render time capture status
  90941. */
  90942. get: function () {
  90943. return this._captureParticlesRenderTime;
  90944. },
  90945. /**
  90946. * Enable or disable the particles render time capture
  90947. */
  90948. set: function (value) {
  90949. var _this = this;
  90950. if (value === this._captureParticlesRenderTime) {
  90951. return;
  90952. }
  90953. this._captureParticlesRenderTime = value;
  90954. if (value) {
  90955. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90956. BABYLON.Tools.StartPerformanceCounter("Particles");
  90957. _this._particlesRenderTime.beginMonitoring();
  90958. });
  90959. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90960. BABYLON.Tools.EndPerformanceCounter("Particles");
  90961. _this._particlesRenderTime.endMonitoring(false);
  90962. });
  90963. }
  90964. else {
  90965. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90966. this._onBeforeParticlesRenderingObserver = null;
  90967. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90968. this._onAfterParticlesRenderingObserver = null;
  90969. }
  90970. },
  90971. enumerable: true,
  90972. configurable: true
  90973. });
  90974. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90975. /**
  90976. * Gets the perf counter used for sprites render time
  90977. */
  90978. get: function () {
  90979. return this._spritesRenderTime;
  90980. },
  90981. enumerable: true,
  90982. configurable: true
  90983. });
  90984. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90985. /**
  90986. * Gets the sprites render time capture status
  90987. */
  90988. get: function () {
  90989. return this._captureSpritesRenderTime;
  90990. },
  90991. /**
  90992. * Enable or disable the sprites render time capture
  90993. */
  90994. set: function (value) {
  90995. var _this = this;
  90996. if (value === this._captureSpritesRenderTime) {
  90997. return;
  90998. }
  90999. this._captureSpritesRenderTime = value;
  91000. if (value) {
  91001. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  91002. BABYLON.Tools.StartPerformanceCounter("Sprites");
  91003. _this._spritesRenderTime.beginMonitoring();
  91004. });
  91005. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  91006. BABYLON.Tools.EndPerformanceCounter("Sprites");
  91007. _this._spritesRenderTime.endMonitoring(false);
  91008. });
  91009. }
  91010. else {
  91011. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91012. this._onBeforeSpritesRenderingObserver = null;
  91013. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91014. this._onAfterSpritesRenderingObserver = null;
  91015. }
  91016. },
  91017. enumerable: true,
  91018. configurable: true
  91019. });
  91020. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  91021. /**
  91022. * Gets the perf counter used for physics time
  91023. */
  91024. get: function () {
  91025. return this._physicsTime;
  91026. },
  91027. enumerable: true,
  91028. configurable: true
  91029. });
  91030. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  91031. /**
  91032. * Gets the physics time capture status
  91033. */
  91034. get: function () {
  91035. return this._capturePhysicsTime;
  91036. },
  91037. /**
  91038. * Enable or disable the physics time capture
  91039. */
  91040. set: function (value) {
  91041. var _this = this;
  91042. if (value === this._capturePhysicsTime) {
  91043. return;
  91044. }
  91045. this._capturePhysicsTime = value;
  91046. if (value) {
  91047. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  91048. BABYLON.Tools.StartPerformanceCounter("Physics");
  91049. _this._physicsTime.beginMonitoring();
  91050. });
  91051. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  91052. BABYLON.Tools.EndPerformanceCounter("Physics");
  91053. _this._physicsTime.endMonitoring();
  91054. });
  91055. }
  91056. else {
  91057. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91058. this._onBeforePhysicsObserver = null;
  91059. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91060. this._onAfterPhysicsObserver = null;
  91061. }
  91062. },
  91063. enumerable: true,
  91064. configurable: true
  91065. });
  91066. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  91067. /**
  91068. * Gets the perf counter used for animations time
  91069. */
  91070. get: function () {
  91071. return this._animationsTime;
  91072. },
  91073. enumerable: true,
  91074. configurable: true
  91075. });
  91076. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  91077. /**
  91078. * Gets the animations time capture status
  91079. */
  91080. get: function () {
  91081. return this._captureAnimationsTime;
  91082. },
  91083. /**
  91084. * Enable or disable the animations time capture
  91085. */
  91086. set: function (value) {
  91087. var _this = this;
  91088. if (value === this._captureAnimationsTime) {
  91089. return;
  91090. }
  91091. this._captureAnimationsTime = value;
  91092. if (value) {
  91093. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  91094. _this._animationsTime.endMonitoring();
  91095. });
  91096. }
  91097. else {
  91098. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91099. this._onAfterAnimationsObserver = null;
  91100. }
  91101. },
  91102. enumerable: true,
  91103. configurable: true
  91104. });
  91105. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  91106. /**
  91107. * Gets the perf counter used for frame time capture
  91108. */
  91109. get: function () {
  91110. return this._frameTime;
  91111. },
  91112. enumerable: true,
  91113. configurable: true
  91114. });
  91115. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  91116. /**
  91117. * Gets the frame time capture status
  91118. */
  91119. get: function () {
  91120. return this._captureFrameTime;
  91121. },
  91122. /**
  91123. * Enable or disable the frame time capture
  91124. */
  91125. set: function (value) {
  91126. this._captureFrameTime = value;
  91127. },
  91128. enumerable: true,
  91129. configurable: true
  91130. });
  91131. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  91132. /**
  91133. * Gets the perf counter used for inter-frames time capture
  91134. */
  91135. get: function () {
  91136. return this._interFrameTime;
  91137. },
  91138. enumerable: true,
  91139. configurable: true
  91140. });
  91141. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  91142. /**
  91143. * Gets the inter-frames time capture status
  91144. */
  91145. get: function () {
  91146. return this._captureInterFrameTime;
  91147. },
  91148. /**
  91149. * Enable or disable the inter-frames time capture
  91150. */
  91151. set: function (value) {
  91152. this._captureInterFrameTime = value;
  91153. },
  91154. enumerable: true,
  91155. configurable: true
  91156. });
  91157. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  91158. /**
  91159. * Gets the perf counter used for render time capture
  91160. */
  91161. get: function () {
  91162. return this._renderTime;
  91163. },
  91164. enumerable: true,
  91165. configurable: true
  91166. });
  91167. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  91168. /**
  91169. * Gets the render time capture status
  91170. */
  91171. get: function () {
  91172. return this._captureRenderTime;
  91173. },
  91174. /**
  91175. * Enable or disable the render time capture
  91176. */
  91177. set: function (value) {
  91178. var _this = this;
  91179. if (value === this._captureRenderTime) {
  91180. return;
  91181. }
  91182. this._captureRenderTime = value;
  91183. if (value) {
  91184. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  91185. _this._renderTime.beginMonitoring();
  91186. BABYLON.Tools.StartPerformanceCounter("Main render");
  91187. });
  91188. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  91189. _this._renderTime.endMonitoring(false);
  91190. BABYLON.Tools.EndPerformanceCounter("Main render");
  91191. });
  91192. }
  91193. else {
  91194. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91195. this._onBeforeDrawPhaseObserver = null;
  91196. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91197. this._onAfterDrawPhaseObserver = null;
  91198. }
  91199. },
  91200. enumerable: true,
  91201. configurable: true
  91202. });
  91203. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  91204. /**
  91205. * Gets the perf counter used for draw calls
  91206. */
  91207. get: function () {
  91208. return this.scene.getEngine()._drawCalls;
  91209. },
  91210. enumerable: true,
  91211. configurable: true
  91212. });
  91213. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  91214. /**
  91215. * Gets the perf counter used for texture collisions
  91216. */
  91217. get: function () {
  91218. return this.scene.getEngine()._textureCollisions;
  91219. },
  91220. enumerable: true,
  91221. configurable: true
  91222. });
  91223. SceneInstrumentation.prototype.dispose = function () {
  91224. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91225. this._onAfterRenderObserver = null;
  91226. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  91227. this._onBeforeActiveMeshesEvaluationObserver = null;
  91228. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  91229. this._onAfterActiveMeshesEvaluationObserver = null;
  91230. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  91231. this._onBeforeRenderTargetsRenderObserver = null;
  91232. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91233. this._onAfterRenderTargetsRenderObserver = null;
  91234. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  91235. this._onBeforeAnimationsObserver = null;
  91236. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91237. this._onBeforeParticlesRenderingObserver = null;
  91238. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91239. this._onAfterParticlesRenderingObserver = null;
  91240. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91241. this._onBeforeSpritesRenderingObserver = null;
  91242. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91243. this._onAfterSpritesRenderingObserver = null;
  91244. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91245. this._onBeforeDrawPhaseObserver = null;
  91246. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91247. this._onAfterDrawPhaseObserver = null;
  91248. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91249. this._onBeforePhysicsObserver = null;
  91250. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91251. this._onAfterPhysicsObserver = null;
  91252. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91253. this._onAfterAnimationsObserver = null;
  91254. this.scene = null;
  91255. };
  91256. return SceneInstrumentation;
  91257. }());
  91258. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91259. })(BABYLON || (BABYLON = {}));
  91260. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91261. "use strict";
  91262. var BABYLON;
  91263. (function (BABYLON) {
  91264. var _TimeToken = /** @class */ (function () {
  91265. function _TimeToken() {
  91266. this._timeElapsedQueryEnded = false;
  91267. }
  91268. return _TimeToken;
  91269. }());
  91270. BABYLON._TimeToken = _TimeToken;
  91271. })(BABYLON || (BABYLON = {}));
  91272. //# sourceMappingURL=babylon.timeToken.js.map
  91273. "use strict";
  91274. var BABYLON;
  91275. (function (BABYLON) {
  91276. /**
  91277. * Background material defines definition.
  91278. * @ignore Mainly internal Use
  91279. */
  91280. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91281. __extends(BackgroundMaterialDefines, _super);
  91282. /**
  91283. * Constructor of the defines.
  91284. */
  91285. function BackgroundMaterialDefines() {
  91286. var _this = _super.call(this) || this;
  91287. /**
  91288. * True if the diffuse texture is in use.
  91289. */
  91290. _this.DIFFUSE = false;
  91291. /**
  91292. * The direct UV channel to use.
  91293. */
  91294. _this.DIFFUSEDIRECTUV = 0;
  91295. /**
  91296. * True if the diffuse texture is in gamma space.
  91297. */
  91298. _this.GAMMADIFFUSE = false;
  91299. /**
  91300. * True if the diffuse texture has opacity in the alpha channel.
  91301. */
  91302. _this.DIFFUSEHASALPHA = false;
  91303. /**
  91304. * True if you want the material to fade to transparent at grazing angle.
  91305. */
  91306. _this.OPACITYFRESNEL = false;
  91307. /**
  91308. * True if an extra blur needs to be added in the reflection.
  91309. */
  91310. _this.REFLECTIONBLUR = false;
  91311. /**
  91312. * True if you want the material to fade to reflection at grazing angle.
  91313. */
  91314. _this.REFLECTIONFRESNEL = false;
  91315. /**
  91316. * True if you want the material to falloff as far as you move away from the scene center.
  91317. */
  91318. _this.REFLECTIONFALLOFF = false;
  91319. /**
  91320. * False if the current Webgl implementation does not support the texture lod extension.
  91321. */
  91322. _this.TEXTURELODSUPPORT = false;
  91323. /**
  91324. * True to ensure the data are premultiplied.
  91325. */
  91326. _this.PREMULTIPLYALPHA = false;
  91327. /**
  91328. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91329. */
  91330. _this.USERGBCOLOR = false;
  91331. /**
  91332. * True to add noise in order to reduce the banding effect.
  91333. */
  91334. _this.NOISE = false;
  91335. /**
  91336. * is the reflection texture in BGR color scheme?
  91337. * Mainly used to solve a bug in ios10 video tag
  91338. */
  91339. _this.REFLECTIONBGR = false;
  91340. _this.IMAGEPROCESSING = false;
  91341. _this.VIGNETTE = false;
  91342. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91343. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91344. _this.TONEMAPPING = false;
  91345. _this.CONTRAST = false;
  91346. _this.COLORCURVES = false;
  91347. _this.COLORGRADING = false;
  91348. _this.COLORGRADING3D = false;
  91349. _this.SAMPLER3DGREENDEPTH = false;
  91350. _this.SAMPLER3DBGRMAP = false;
  91351. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91352. _this.EXPOSURE = false;
  91353. // Reflection.
  91354. _this.REFLECTION = false;
  91355. _this.REFLECTIONMAP_3D = false;
  91356. _this.REFLECTIONMAP_SPHERICAL = false;
  91357. _this.REFLECTIONMAP_PLANAR = false;
  91358. _this.REFLECTIONMAP_CUBIC = false;
  91359. _this.REFLECTIONMAP_PROJECTION = false;
  91360. _this.REFLECTIONMAP_SKYBOX = false;
  91361. _this.REFLECTIONMAP_EXPLICIT = false;
  91362. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91363. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91364. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91365. _this.INVERTCUBICMAP = false;
  91366. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91367. _this.LODINREFLECTIONALPHA = false;
  91368. _this.GAMMAREFLECTION = false;
  91369. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91370. // Default BJS.
  91371. _this.MAINUV1 = false;
  91372. _this.MAINUV2 = false;
  91373. _this.UV1 = false;
  91374. _this.UV2 = false;
  91375. _this.CLIPPLANE = false;
  91376. _this.POINTSIZE = false;
  91377. _this.FOG = false;
  91378. _this.NORMAL = false;
  91379. _this.NUM_BONE_INFLUENCERS = 0;
  91380. _this.BonesPerMesh = 0;
  91381. _this.INSTANCES = false;
  91382. _this.SHADOWFLOAT = false;
  91383. _this.rebuild();
  91384. return _this;
  91385. }
  91386. return BackgroundMaterialDefines;
  91387. }(BABYLON.MaterialDefines));
  91388. /**
  91389. * Background material used to create an efficient environement around your scene.
  91390. */
  91391. var BackgroundMaterial = /** @class */ (function (_super) {
  91392. __extends(BackgroundMaterial, _super);
  91393. /**
  91394. * Instantiates a Background Material in the given scene
  91395. * @param name The friendly name of the material
  91396. * @param scene The scene to add the material to
  91397. */
  91398. function BackgroundMaterial(name, scene) {
  91399. var _this = _super.call(this, name, scene) || this;
  91400. /**
  91401. * Key light Color (multiply against the R channel of the environement texture)
  91402. */
  91403. _this.primaryColor = BABYLON.Color3.White();
  91404. /**
  91405. * Key light Level (allowing HDR output of the background)
  91406. */
  91407. _this.primaryLevel = 1;
  91408. /**
  91409. * Secondary light Color (multiply against the G channel of the environement texture)
  91410. */
  91411. _this.secondaryColor = BABYLON.Color3.Gray();
  91412. /**
  91413. * Secondary light Level (allowing HDR output of the background)
  91414. */
  91415. _this.secondaryLevel = 1;
  91416. /**
  91417. * Tertiary light Color (multiply against the B channel of the environement texture)
  91418. */
  91419. _this.tertiaryColor = BABYLON.Color3.Black();
  91420. /**
  91421. * Tertiary light Level (allowing HDR output of the background)
  91422. */
  91423. _this.tertiaryLevel = 1;
  91424. /**
  91425. * Reflection Texture used in the material.
  91426. * Should be author in a specific way for the best result (refer to the documentation).
  91427. */
  91428. _this.reflectionTexture = null;
  91429. /**
  91430. * Reflection Texture level of blur.
  91431. *
  91432. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91433. * texture twice.
  91434. */
  91435. _this.reflectionBlur = 0;
  91436. /**
  91437. * Diffuse Texture used in the material.
  91438. * Should be author in a specific way for the best result (refer to the documentation).
  91439. */
  91440. _this.diffuseTexture = null;
  91441. _this._shadowLights = null;
  91442. /**
  91443. * Specify the list of lights casting shadow on the material.
  91444. * All scene shadow lights will be included if null.
  91445. */
  91446. _this.shadowLights = null;
  91447. /**
  91448. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91449. * soft lighting on the background.
  91450. */
  91451. _this.shadowBlurScale = 1;
  91452. /**
  91453. * Helps adjusting the shadow to a softer level if required.
  91454. * 0 means black shadows and 1 means no shadows.
  91455. */
  91456. _this.shadowLevel = 0;
  91457. /**
  91458. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91459. * It is usually zero but might be interesting to modify according to your setup.
  91460. */
  91461. _this.sceneCenter = BABYLON.Vector3.Zero();
  91462. /**
  91463. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91464. * This helps ensuring a nice transition when the camera goes under the ground.
  91465. */
  91466. _this.opacityFresnel = true;
  91467. /**
  91468. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91469. * This helps adding a mirror texture on the ground.
  91470. */
  91471. _this.reflectionFresnel = false;
  91472. /**
  91473. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91474. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91475. */
  91476. _this.reflectionFalloffDistance = 0.0;
  91477. /**
  91478. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91479. */
  91480. _this.reflectionAmount = 1.0;
  91481. /**
  91482. * This specifies the weight of the reflection at grazing angle.
  91483. */
  91484. _this.reflectionReflectance0 = 0.05;
  91485. /**
  91486. * This specifies the weight of the reflection at a perpendicular point of view.
  91487. */
  91488. _this.reflectionReflectance90 = 0.5;
  91489. /**
  91490. * Helps to directly use the maps channels instead of their level.
  91491. */
  91492. _this.useRGBColor = true;
  91493. /**
  91494. * This helps reducing the banding effect that could occur on the background.
  91495. */
  91496. _this.enableNoise = false;
  91497. _this._fovMultiplier = 1.0;
  91498. /**
  91499. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91500. * @type {boolean}
  91501. */
  91502. _this.useEquirectangularFOV = false;
  91503. _this._maxSimultaneousLights = 4;
  91504. /**
  91505. * Number of Simultaneous lights allowed on the material.
  91506. */
  91507. _this.maxSimultaneousLights = 4;
  91508. /**
  91509. * Keep track of the image processing observer to allow dispose and replace.
  91510. */
  91511. _this._imageProcessingObserver = null;
  91512. /**
  91513. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91514. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91515. */
  91516. _this.switchToBGR = false;
  91517. // Temp values kept as cache in the material.
  91518. _this._renderTargets = new BABYLON.SmartArray(16);
  91519. _this._reflectionControls = BABYLON.Vector4.Zero();
  91520. // Setup the default processing configuration to the scene.
  91521. _this._attachImageProcessingConfiguration(null);
  91522. _this.getRenderTargetTextures = function () {
  91523. _this._renderTargets.reset();
  91524. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91525. _this._renderTargets.push(_this._diffuseTexture);
  91526. }
  91527. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91528. _this._renderTargets.push(_this._reflectionTexture);
  91529. }
  91530. return _this._renderTargets;
  91531. };
  91532. return _this;
  91533. }
  91534. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91535. /**
  91536. * Sets the reflection reflectance fresnel values according to the default standard
  91537. * empirically know to work well :-)
  91538. */
  91539. set: function (value) {
  91540. var reflectionWeight = value;
  91541. if (reflectionWeight < 0.5) {
  91542. reflectionWeight = reflectionWeight * 2.0;
  91543. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91544. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91545. }
  91546. else {
  91547. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91548. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91549. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91550. }
  91551. },
  91552. enumerable: true,
  91553. configurable: true
  91554. });
  91555. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91556. /**
  91557. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91558. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91559. * Recommended to be keep at 1.0 except for special cases.
  91560. */
  91561. get: function () {
  91562. return this._fovMultiplier;
  91563. },
  91564. set: function (value) {
  91565. if (isNaN(value)) {
  91566. value = 1.0;
  91567. }
  91568. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91569. },
  91570. enumerable: true,
  91571. configurable: true
  91572. });
  91573. /**
  91574. * Attaches a new image processing configuration to the PBR Material.
  91575. * @param configuration (if null the scene configuration will be use)
  91576. */
  91577. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91578. var _this = this;
  91579. if (configuration === this._imageProcessingConfiguration) {
  91580. return;
  91581. }
  91582. // Detaches observer.
  91583. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91584. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91585. }
  91586. // Pick the scene configuration if needed.
  91587. if (!configuration) {
  91588. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91589. }
  91590. else {
  91591. this._imageProcessingConfiguration = configuration;
  91592. }
  91593. // Attaches observer.
  91594. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91595. _this._markAllSubMeshesAsImageProcessingDirty();
  91596. });
  91597. };
  91598. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91599. /**
  91600. * Gets the image processing configuration used either in this material.
  91601. */
  91602. get: function () {
  91603. return this._imageProcessingConfiguration;
  91604. },
  91605. /**
  91606. * Sets the Default image processing configuration used either in the this material.
  91607. *
  91608. * If sets to null, the scene one is in use.
  91609. */
  91610. set: function (value) {
  91611. this._attachImageProcessingConfiguration(value);
  91612. // Ensure the effect will be rebuilt.
  91613. this._markAllSubMeshesAsTexturesDirty();
  91614. },
  91615. enumerable: true,
  91616. configurable: true
  91617. });
  91618. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91619. /**
  91620. * Gets wether the color curves effect is enabled.
  91621. */
  91622. get: function () {
  91623. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91624. },
  91625. /**
  91626. * Sets wether the color curves effect is enabled.
  91627. */
  91628. set: function (value) {
  91629. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91630. },
  91631. enumerable: true,
  91632. configurable: true
  91633. });
  91634. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91635. /**
  91636. * Gets wether the color grading effect is enabled.
  91637. */
  91638. get: function () {
  91639. return this.imageProcessingConfiguration.colorGradingEnabled;
  91640. },
  91641. /**
  91642. * Gets wether the color grading effect is enabled.
  91643. */
  91644. set: function (value) {
  91645. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91646. },
  91647. enumerable: true,
  91648. configurable: true
  91649. });
  91650. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91651. /**
  91652. * Gets wether tonemapping is enabled or not.
  91653. */
  91654. get: function () {
  91655. return this._imageProcessingConfiguration.toneMappingEnabled;
  91656. },
  91657. /**
  91658. * Sets wether tonemapping is enabled or not
  91659. */
  91660. set: function (value) {
  91661. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91662. },
  91663. enumerable: true,
  91664. configurable: true
  91665. });
  91666. ;
  91667. ;
  91668. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91669. /**
  91670. * The camera exposure used on this material.
  91671. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91672. * This corresponds to a photographic exposure.
  91673. */
  91674. get: function () {
  91675. return this._imageProcessingConfiguration.exposure;
  91676. },
  91677. /**
  91678. * The camera exposure used on this material.
  91679. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91680. * This corresponds to a photographic exposure.
  91681. */
  91682. set: function (value) {
  91683. this._imageProcessingConfiguration.exposure = value;
  91684. },
  91685. enumerable: true,
  91686. configurable: true
  91687. });
  91688. ;
  91689. ;
  91690. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91691. /**
  91692. * Gets The camera contrast used on this material.
  91693. */
  91694. get: function () {
  91695. return this._imageProcessingConfiguration.contrast;
  91696. },
  91697. /**
  91698. * Sets The camera contrast used on this material.
  91699. */
  91700. set: function (value) {
  91701. this._imageProcessingConfiguration.contrast = value;
  91702. },
  91703. enumerable: true,
  91704. configurable: true
  91705. });
  91706. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91707. /**
  91708. * Gets the Color Grading 2D Lookup Texture.
  91709. */
  91710. get: function () {
  91711. return this._imageProcessingConfiguration.colorGradingTexture;
  91712. },
  91713. /**
  91714. * Sets the Color Grading 2D Lookup Texture.
  91715. */
  91716. set: function (value) {
  91717. this.imageProcessingConfiguration.colorGradingTexture = value;
  91718. },
  91719. enumerable: true,
  91720. configurable: true
  91721. });
  91722. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91723. /**
  91724. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91725. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91726. * 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;
  91727. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91728. */
  91729. get: function () {
  91730. return this.imageProcessingConfiguration.colorCurves;
  91731. },
  91732. /**
  91733. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91734. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91735. * 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;
  91736. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91737. */
  91738. set: function (value) {
  91739. this.imageProcessingConfiguration.colorCurves = value;
  91740. },
  91741. enumerable: true,
  91742. configurable: true
  91743. });
  91744. /**
  91745. * The entire material has been created in order to prevent overdraw.
  91746. * @returns false
  91747. */
  91748. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91749. return true;
  91750. };
  91751. /**
  91752. * The entire material has been created in order to prevent overdraw.
  91753. * @returns true if blending is enable
  91754. */
  91755. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91756. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91757. };
  91758. /**
  91759. * Checks wether the material is ready to be rendered for a given mesh.
  91760. * @param mesh The mesh to render
  91761. * @param subMesh The submesh to check against
  91762. * @param useInstances Specify wether or not the material is used with instances
  91763. * @returns true if all the dependencies are ready (Textures, Effects...)
  91764. */
  91765. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91766. var _this = this;
  91767. if (useInstances === void 0) { useInstances = false; }
  91768. if (subMesh.effect && this.isFrozen) {
  91769. if (this._wasPreviouslyReady) {
  91770. return true;
  91771. }
  91772. }
  91773. if (!subMesh._materialDefines) {
  91774. subMesh._materialDefines = new BackgroundMaterialDefines();
  91775. }
  91776. var scene = this.getScene();
  91777. var defines = subMesh._materialDefines;
  91778. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91779. if (defines._renderId === scene.getRenderId()) {
  91780. return true;
  91781. }
  91782. }
  91783. var engine = scene.getEngine();
  91784. // Lights
  91785. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91786. defines._needNormals = true;
  91787. // Textures
  91788. if (defines._areTexturesDirty) {
  91789. defines._needUVs = false;
  91790. if (scene.texturesEnabled) {
  91791. if (scene.getEngine().getCaps().textureLOD) {
  91792. defines.TEXTURELODSUPPORT = true;
  91793. }
  91794. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91795. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91796. return false;
  91797. }
  91798. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91799. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91800. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91801. defines.OPACITYFRESNEL = this._opacityFresnel;
  91802. }
  91803. else {
  91804. defines.DIFFUSE = false;
  91805. defines.DIFFUSEHASALPHA = false;
  91806. defines.GAMMADIFFUSE = false;
  91807. defines.OPACITYFRESNEL = false;
  91808. }
  91809. var reflectionTexture = this._reflectionTexture;
  91810. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91811. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91812. return false;
  91813. }
  91814. defines.REFLECTION = true;
  91815. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91816. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91817. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91818. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91819. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91820. defines.REFLECTIONBGR = this.switchToBGR;
  91821. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91822. defines.INVERTCUBICMAP = true;
  91823. }
  91824. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91825. switch (reflectionTexture.coordinatesMode) {
  91826. case BABYLON.Texture.CUBIC_MODE:
  91827. case BABYLON.Texture.INVCUBIC_MODE:
  91828. defines.REFLECTIONMAP_CUBIC = true;
  91829. break;
  91830. case BABYLON.Texture.EXPLICIT_MODE:
  91831. defines.REFLECTIONMAP_EXPLICIT = true;
  91832. break;
  91833. case BABYLON.Texture.PLANAR_MODE:
  91834. defines.REFLECTIONMAP_PLANAR = true;
  91835. break;
  91836. case BABYLON.Texture.PROJECTION_MODE:
  91837. defines.REFLECTIONMAP_PROJECTION = true;
  91838. break;
  91839. case BABYLON.Texture.SKYBOX_MODE:
  91840. defines.REFLECTIONMAP_SKYBOX = true;
  91841. break;
  91842. case BABYLON.Texture.SPHERICAL_MODE:
  91843. defines.REFLECTIONMAP_SPHERICAL = true;
  91844. break;
  91845. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91846. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91847. break;
  91848. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91849. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91850. break;
  91851. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91852. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91853. break;
  91854. }
  91855. if (this.reflectionFresnel) {
  91856. defines.REFLECTIONFRESNEL = true;
  91857. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91858. this._reflectionControls.x = this.reflectionAmount;
  91859. this._reflectionControls.y = this.reflectionReflectance0;
  91860. this._reflectionControls.z = this.reflectionReflectance90;
  91861. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91862. }
  91863. else {
  91864. defines.REFLECTIONFRESNEL = false;
  91865. defines.REFLECTIONFALLOFF = false;
  91866. }
  91867. }
  91868. else {
  91869. defines.REFLECTION = false;
  91870. defines.REFLECTIONFALLOFF = false;
  91871. defines.REFLECTIONBLUR = false;
  91872. defines.REFLECTIONMAP_3D = false;
  91873. defines.REFLECTIONMAP_SPHERICAL = false;
  91874. defines.REFLECTIONMAP_PLANAR = false;
  91875. defines.REFLECTIONMAP_CUBIC = false;
  91876. defines.REFLECTIONMAP_PROJECTION = false;
  91877. defines.REFLECTIONMAP_SKYBOX = false;
  91878. defines.REFLECTIONMAP_EXPLICIT = false;
  91879. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91880. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91881. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91882. defines.INVERTCUBICMAP = false;
  91883. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91884. defines.LODINREFLECTIONALPHA = false;
  91885. defines.GAMMAREFLECTION = false;
  91886. }
  91887. }
  91888. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91889. defines.USERGBCOLOR = this._useRGBColor;
  91890. defines.NOISE = this._enableNoise;
  91891. }
  91892. if (defines._areImageProcessingDirty) {
  91893. if (!this._imageProcessingConfiguration.isReady()) {
  91894. return false;
  91895. }
  91896. this._imageProcessingConfiguration.prepareDefines(defines);
  91897. }
  91898. // Misc.
  91899. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91900. // Values that need to be evaluated on every frame
  91901. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91902. // Attribs
  91903. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91904. if (mesh) {
  91905. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91906. mesh.createNormals(true);
  91907. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91908. }
  91909. }
  91910. }
  91911. // Get correct effect
  91912. if (defines.isDirty) {
  91913. defines.markAsProcessed();
  91914. scene.resetCachedMaterial();
  91915. // Fallbacks
  91916. var fallbacks = new BABYLON.EffectFallbacks();
  91917. if (defines.FOG) {
  91918. fallbacks.addFallback(0, "FOG");
  91919. }
  91920. if (defines.POINTSIZE) {
  91921. fallbacks.addFallback(1, "POINTSIZE");
  91922. }
  91923. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91924. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91925. fallbacks.addCPUSkinningFallback(0, mesh);
  91926. }
  91927. //Attributes
  91928. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91929. if (defines.NORMAL) {
  91930. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91931. }
  91932. if (defines.UV1) {
  91933. attribs.push(BABYLON.VertexBuffer.UVKind);
  91934. }
  91935. if (defines.UV2) {
  91936. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91937. }
  91938. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91939. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91940. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91941. "vFogInfos", "vFogColor", "pointSize",
  91942. "vClipPlane", "mBones",
  91943. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91944. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91945. "shadowLevel", "alpha",
  91946. "vBackgroundCenter", "vReflectionControl",
  91947. "vDiffuseInfos", "diffuseMatrix",
  91948. ];
  91949. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91950. var uniformBuffers = ["Material", "Scene"];
  91951. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91952. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91953. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91954. uniformsNames: uniforms,
  91955. uniformBuffersNames: uniformBuffers,
  91956. samplers: samplers,
  91957. defines: defines,
  91958. maxSimultaneousLights: this._maxSimultaneousLights
  91959. });
  91960. var onCompiled = function (effect) {
  91961. if (_this.onCompiled) {
  91962. _this.onCompiled(effect);
  91963. }
  91964. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91965. };
  91966. var join = defines.toString();
  91967. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91968. attributes: attribs,
  91969. uniformsNames: uniforms,
  91970. uniformBuffersNames: uniformBuffers,
  91971. samplers: samplers,
  91972. defines: join,
  91973. fallbacks: fallbacks,
  91974. onCompiled: onCompiled,
  91975. onError: this.onError,
  91976. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91977. }, engine), defines);
  91978. this.buildUniformLayout();
  91979. }
  91980. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91981. return false;
  91982. }
  91983. defines._renderId = scene.getRenderId();
  91984. this._wasPreviouslyReady = true;
  91985. return true;
  91986. };
  91987. /**
  91988. * Build the uniform buffer used in the material.
  91989. */
  91990. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91991. // Order is important !
  91992. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91993. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91994. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91995. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91996. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91997. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91998. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91999. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  92000. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  92001. this._uniformBuffer.addUniform("pointSize", 1);
  92002. this._uniformBuffer.addUniform("shadowLevel", 1);
  92003. this._uniformBuffer.addUniform("alpha", 1);
  92004. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  92005. this._uniformBuffer.addUniform("vReflectionControl", 4);
  92006. this._uniformBuffer.create();
  92007. };
  92008. /**
  92009. * Unbind the material.
  92010. */
  92011. BackgroundMaterial.prototype.unbind = function () {
  92012. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  92013. this._uniformBuffer.setTexture("diffuseSampler", null);
  92014. }
  92015. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  92016. this._uniformBuffer.setTexture("reflectionSampler", null);
  92017. }
  92018. _super.prototype.unbind.call(this);
  92019. };
  92020. /**
  92021. * Bind only the world matrix to the material.
  92022. * @param world The world matrix to bind.
  92023. */
  92024. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  92025. this._activeEffect.setMatrix("world", world);
  92026. };
  92027. /**
  92028. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  92029. * @param world The world matrix to bind.
  92030. * @param subMesh The submesh to bind for.
  92031. */
  92032. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  92033. var scene = this.getScene();
  92034. var defines = subMesh._materialDefines;
  92035. if (!defines) {
  92036. return;
  92037. }
  92038. var effect = subMesh.effect;
  92039. if (!effect) {
  92040. return;
  92041. }
  92042. this._activeEffect = effect;
  92043. // Matrices
  92044. this.bindOnlyWorldMatrix(world);
  92045. // Bones
  92046. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  92047. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  92048. if (mustRebind) {
  92049. this._uniformBuffer.bindToEffect(effect, "Material");
  92050. this.bindViewProjection(effect);
  92051. var reflectionTexture = this._reflectionTexture;
  92052. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  92053. // Texture uniforms
  92054. if (scene.texturesEnabled) {
  92055. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92056. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  92057. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  92058. }
  92059. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92060. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  92061. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  92062. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  92063. }
  92064. }
  92065. if (this.shadowLevel > 0) {
  92066. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  92067. }
  92068. this._uniformBuffer.updateFloat("alpha", this.alpha);
  92069. // Point size
  92070. if (this.pointsCloud) {
  92071. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  92072. }
  92073. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  92074. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  92075. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  92076. }
  92077. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  92078. // Textures
  92079. if (scene.texturesEnabled) {
  92080. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92081. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  92082. }
  92083. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92084. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  92085. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  92086. }
  92087. else if (!defines.REFLECTIONBLUR) {
  92088. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  92089. }
  92090. else {
  92091. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  92092. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  92093. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  92094. }
  92095. if (defines.REFLECTIONFRESNEL) {
  92096. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  92097. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  92098. }
  92099. }
  92100. }
  92101. // Clip plane
  92102. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  92103. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  92104. }
  92105. if (mustRebind || !this.isFrozen) {
  92106. if (scene.lightsEnabled) {
  92107. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  92108. }
  92109. // View
  92110. this.bindView(effect);
  92111. // Fog
  92112. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  92113. // image processing
  92114. this._imageProcessingConfiguration.bind(this._activeEffect);
  92115. }
  92116. this._uniformBuffer.update();
  92117. this._afterBind(mesh);
  92118. };
  92119. /**
  92120. * Dispose the material.
  92121. * @param forceDisposeEffect Force disposal of the associated effect.
  92122. * @param forceDisposeTextures Force disposal of the associated textures.
  92123. */
  92124. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  92125. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  92126. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  92127. if (forceDisposeTextures) {
  92128. if (this.diffuseTexture) {
  92129. this.diffuseTexture.dispose();
  92130. }
  92131. if (this.reflectionTexture) {
  92132. this.reflectionTexture.dispose();
  92133. }
  92134. }
  92135. this._renderTargets.dispose();
  92136. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  92137. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  92138. }
  92139. _super.prototype.dispose.call(this, forceDisposeEffect);
  92140. };
  92141. /**
  92142. * Clones the material.
  92143. * @param name The cloned name.
  92144. * @returns The cloned material.
  92145. */
  92146. BackgroundMaterial.prototype.clone = function (name) {
  92147. var _this = this;
  92148. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  92149. };
  92150. /**
  92151. * Serializes the current material to its JSON representation.
  92152. * @returns The JSON representation.
  92153. */
  92154. BackgroundMaterial.prototype.serialize = function () {
  92155. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92156. serializationObject.customType = "BABYLON.BackgroundMaterial";
  92157. return serializationObject;
  92158. };
  92159. /**
  92160. * Gets the class name of the material
  92161. * @returns "BackgroundMaterial"
  92162. */
  92163. BackgroundMaterial.prototype.getClassName = function () {
  92164. return "BackgroundMaterial";
  92165. };
  92166. /**
  92167. * Parse a JSON input to create back a background material.
  92168. * @param source The JSON data to parse
  92169. * @param scene The scene to create the parsed material in
  92170. * @param rootUrl The root url of the assets the material depends upon
  92171. * @returns the instantiated BackgroundMaterial.
  92172. */
  92173. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  92174. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  92175. };
  92176. /**
  92177. * Standard reflectance value at parallel view angle.
  92178. */
  92179. BackgroundMaterial.StandardReflectance0 = 0.05;
  92180. /**
  92181. * Standard reflectance value at grazing angle.
  92182. */
  92183. BackgroundMaterial.StandardReflectance90 = 0.5;
  92184. __decorate([
  92185. BABYLON.serializeAsColor3()
  92186. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  92187. __decorate([
  92188. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92189. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  92190. __decorate([
  92191. BABYLON.serialize()
  92192. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  92193. __decorate([
  92194. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92195. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  92196. __decorate([
  92197. BABYLON.serializeAsColor3()
  92198. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  92199. __decorate([
  92200. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92201. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  92202. __decorate([
  92203. BABYLON.serialize()
  92204. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  92205. __decorate([
  92206. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92207. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  92208. __decorate([
  92209. BABYLON.serializeAsColor3()
  92210. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  92211. __decorate([
  92212. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92213. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  92214. __decorate([
  92215. BABYLON.serialize()
  92216. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  92217. __decorate([
  92218. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92219. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  92220. __decorate([
  92221. BABYLON.serializeAsTexture()
  92222. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  92223. __decorate([
  92224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92225. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  92226. __decorate([
  92227. BABYLON.serialize()
  92228. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  92229. __decorate([
  92230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92231. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  92232. __decorate([
  92233. BABYLON.serializeAsTexture()
  92234. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  92235. __decorate([
  92236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92237. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  92238. __decorate([
  92239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92240. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  92241. __decorate([
  92242. BABYLON.serialize()
  92243. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  92244. __decorate([
  92245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92246. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92247. __decorate([
  92248. BABYLON.serialize()
  92249. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92250. __decorate([
  92251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92252. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92253. __decorate([
  92254. BABYLON.serializeAsVector3()
  92255. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92256. __decorate([
  92257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92258. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92259. __decorate([
  92260. BABYLON.serialize()
  92261. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92262. __decorate([
  92263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92264. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92265. __decorate([
  92266. BABYLON.serialize()
  92267. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92268. __decorate([
  92269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92270. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92271. __decorate([
  92272. BABYLON.serialize()
  92273. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92274. __decorate([
  92275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92276. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92277. __decorate([
  92278. BABYLON.serialize()
  92279. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92280. __decorate([
  92281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92282. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92283. __decorate([
  92284. BABYLON.serialize()
  92285. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92286. __decorate([
  92287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92288. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92289. __decorate([
  92290. BABYLON.serialize()
  92291. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92292. __decorate([
  92293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92294. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92295. __decorate([
  92296. BABYLON.serialize()
  92297. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92298. __decorate([
  92299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92300. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92301. __decorate([
  92302. BABYLON.serialize()
  92303. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92304. __decorate([
  92305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92306. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92307. __decorate([
  92308. BABYLON.serialize()
  92309. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92310. __decorate([
  92311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92312. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92313. __decorate([
  92314. BABYLON.serializeAsImageProcessingConfiguration()
  92315. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92316. return BackgroundMaterial;
  92317. }(BABYLON.PushMaterial));
  92318. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92319. })(BABYLON || (BABYLON = {}));
  92320. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92321. "use strict";
  92322. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92323. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92324. s = arguments[i];
  92325. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92326. t[p] = s[p];
  92327. }
  92328. return t;
  92329. };
  92330. var BABYLON;
  92331. (function (BABYLON) {
  92332. /**
  92333. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92334. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92335. * It also helps with the default setup of your imageProcessing configuration.
  92336. */
  92337. var EnvironmentHelper = /** @class */ (function () {
  92338. /**
  92339. * constructor
  92340. * @param options
  92341. * @param scene The scene to add the material to
  92342. */
  92343. function EnvironmentHelper(options, scene) {
  92344. var _this = this;
  92345. this._errorHandler = function (message, exception) {
  92346. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92347. };
  92348. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92349. this._scene = scene;
  92350. this.onErrorObservable = new BABYLON.Observable();
  92351. this._setupBackground();
  92352. this._setupImageProcessing();
  92353. }
  92354. /**
  92355. * Creates the default options for the helper.
  92356. */
  92357. EnvironmentHelper._getDefaultOptions = function () {
  92358. return {
  92359. createGround: true,
  92360. groundSize: 15,
  92361. groundTexture: this._groundTextureCDNUrl,
  92362. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92363. groundOpacity: 0.9,
  92364. enableGroundShadow: true,
  92365. groundShadowLevel: 0.5,
  92366. enableGroundMirror: false,
  92367. groundMirrorSizeRatio: 0.3,
  92368. groundMirrorBlurKernel: 64,
  92369. groundMirrorAmount: 1,
  92370. groundMirrorFresnelWeight: 1,
  92371. groundMirrorFallOffDistance: 0,
  92372. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92373. groundYBias: 0.00001,
  92374. createSkybox: true,
  92375. skyboxSize: 20,
  92376. skyboxTexture: this._skyboxTextureCDNUrl,
  92377. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92378. backgroundYRotation: 0,
  92379. sizeAuto: true,
  92380. rootPosition: BABYLON.Vector3.Zero(),
  92381. setupImageProcessing: true,
  92382. environmentTexture: this._environmentTextureCDNUrl,
  92383. cameraExposure: 0.8,
  92384. cameraContrast: 1.2,
  92385. toneMappingEnabled: true,
  92386. };
  92387. };
  92388. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92389. /**
  92390. * Gets the root mesh created by the helper.
  92391. */
  92392. get: function () {
  92393. return this._rootMesh;
  92394. },
  92395. enumerable: true,
  92396. configurable: true
  92397. });
  92398. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92399. /**
  92400. * Gets the skybox created by the helper.
  92401. */
  92402. get: function () {
  92403. return this._skybox;
  92404. },
  92405. enumerable: true,
  92406. configurable: true
  92407. });
  92408. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92409. /**
  92410. * Gets the skybox texture created by the helper.
  92411. */
  92412. get: function () {
  92413. return this._skyboxTexture;
  92414. },
  92415. enumerable: true,
  92416. configurable: true
  92417. });
  92418. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92419. /**
  92420. * Gets the skybox material created by the helper.
  92421. */
  92422. get: function () {
  92423. return this._skyboxMaterial;
  92424. },
  92425. enumerable: true,
  92426. configurable: true
  92427. });
  92428. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92429. /**
  92430. * Gets the ground mesh created by the helper.
  92431. */
  92432. get: function () {
  92433. return this._ground;
  92434. },
  92435. enumerable: true,
  92436. configurable: true
  92437. });
  92438. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92439. /**
  92440. * Gets the ground texture created by the helper.
  92441. */
  92442. get: function () {
  92443. return this._groundTexture;
  92444. },
  92445. enumerable: true,
  92446. configurable: true
  92447. });
  92448. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92449. /**
  92450. * Gets the ground mirror created by the helper.
  92451. */
  92452. get: function () {
  92453. return this._groundMirror;
  92454. },
  92455. enumerable: true,
  92456. configurable: true
  92457. });
  92458. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92459. /**
  92460. * Gets the ground mirror render list to helps pushing the meshes
  92461. * you wish in the ground reflection.
  92462. */
  92463. get: function () {
  92464. if (this._groundMirror) {
  92465. return this._groundMirror.renderList;
  92466. }
  92467. return null;
  92468. },
  92469. enumerable: true,
  92470. configurable: true
  92471. });
  92472. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92473. /**
  92474. * Gets the ground material created by the helper.
  92475. */
  92476. get: function () {
  92477. return this._groundMaterial;
  92478. },
  92479. enumerable: true,
  92480. configurable: true
  92481. });
  92482. /**
  92483. * Updates the background according to the new options
  92484. * @param options
  92485. */
  92486. EnvironmentHelper.prototype.updateOptions = function (options) {
  92487. var newOptions = __assign({}, this._options, options);
  92488. if (this._ground && !newOptions.createGround) {
  92489. this._ground.dispose();
  92490. this._ground = null;
  92491. }
  92492. if (this._groundMaterial && !newOptions.createGround) {
  92493. this._groundMaterial.dispose();
  92494. this._groundMaterial = null;
  92495. }
  92496. if (this._groundTexture) {
  92497. if (this._options.groundTexture != newOptions.groundTexture) {
  92498. this._groundTexture.dispose();
  92499. this._groundTexture = null;
  92500. }
  92501. }
  92502. if (this._skybox && !newOptions.createSkybox) {
  92503. this._skybox.dispose();
  92504. this._skybox = null;
  92505. }
  92506. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92507. this._skyboxMaterial.dispose();
  92508. this._skyboxMaterial = null;
  92509. }
  92510. if (this._skyboxTexture) {
  92511. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92512. this._skyboxTexture.dispose();
  92513. this._skyboxTexture = null;
  92514. }
  92515. }
  92516. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92517. this._groundMirror.dispose();
  92518. this._groundMirror = null;
  92519. }
  92520. if (this._scene.environmentTexture) {
  92521. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92522. this._scene.environmentTexture.dispose();
  92523. }
  92524. }
  92525. this._options = newOptions;
  92526. this._setupBackground();
  92527. this._setupImageProcessing();
  92528. };
  92529. /**
  92530. * Sets the primary color of all the available elements.
  92531. * @param color
  92532. */
  92533. EnvironmentHelper.prototype.setMainColor = function (color) {
  92534. if (this.groundMaterial) {
  92535. this.groundMaterial.primaryColor = color;
  92536. }
  92537. if (this.skyboxMaterial) {
  92538. this.skyboxMaterial.primaryColor = color;
  92539. }
  92540. if (this.groundMirror) {
  92541. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92542. }
  92543. };
  92544. /**
  92545. * Setup the image processing according to the specified options.
  92546. */
  92547. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92548. if (this._options.setupImageProcessing) {
  92549. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92550. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92551. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92552. this._setupEnvironmentTexture();
  92553. }
  92554. };
  92555. /**
  92556. * Setup the environment texture according to the specified options.
  92557. */
  92558. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92559. if (this._scene.environmentTexture) {
  92560. return;
  92561. }
  92562. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92563. this._scene.environmentTexture = this._options.environmentTexture;
  92564. return;
  92565. }
  92566. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92567. this._scene.environmentTexture = environmentTexture;
  92568. };
  92569. /**
  92570. * Setup the background according to the specified options.
  92571. */
  92572. EnvironmentHelper.prototype._setupBackground = function () {
  92573. if (!this._rootMesh) {
  92574. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92575. }
  92576. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92577. var sceneSize = this._getSceneSize();
  92578. if (this._options.createGround) {
  92579. this._setupGround(sceneSize);
  92580. this._setupGroundMaterial();
  92581. this._setupGroundDiffuseTexture();
  92582. if (this._options.enableGroundMirror) {
  92583. this._setupGroundMirrorTexture(sceneSize);
  92584. }
  92585. this._setupMirrorInGroundMaterial();
  92586. }
  92587. if (this._options.createSkybox) {
  92588. this._setupSkybox(sceneSize);
  92589. this._setupSkyboxMaterial();
  92590. this._setupSkyboxReflectionTexture();
  92591. }
  92592. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92593. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92594. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92595. };
  92596. /**
  92597. * Get the scene sizes according to the setup.
  92598. */
  92599. EnvironmentHelper.prototype._getSceneSize = function () {
  92600. var _this = this;
  92601. var groundSize = this._options.groundSize;
  92602. var skyboxSize = this._options.skyboxSize;
  92603. var rootPosition = this._options.rootPosition;
  92604. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92605. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92606. }
  92607. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92608. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92609. });
  92610. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92611. if (this._options.sizeAuto) {
  92612. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92613. this._scene.activeCamera.upperRadiusLimit) {
  92614. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92615. skyboxSize = groundSize;
  92616. }
  92617. var sceneDiagonalLenght = sceneDiagonal.length();
  92618. if (sceneDiagonalLenght > groundSize) {
  92619. groundSize = sceneDiagonalLenght * 2;
  92620. skyboxSize = groundSize;
  92621. }
  92622. // 10 % bigger.
  92623. groundSize *= 1.1;
  92624. skyboxSize *= 1.5;
  92625. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92626. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92627. }
  92628. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92629. };
  92630. /**
  92631. * Setup the ground according to the specified options.
  92632. */
  92633. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92634. var _this = this;
  92635. if (!this._ground) {
  92636. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92637. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92638. this._ground.parent = this._rootMesh;
  92639. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92640. }
  92641. this._ground.receiveShadows = this._options.enableGroundShadow;
  92642. };
  92643. /**
  92644. * Setup the ground material according to the specified options.
  92645. */
  92646. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92647. if (!this._groundMaterial) {
  92648. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92649. }
  92650. this._groundMaterial.alpha = this._options.groundOpacity;
  92651. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92652. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92653. this._groundMaterial.primaryLevel = 1;
  92654. this._groundMaterial.primaryColor = this._options.groundColor;
  92655. this._groundMaterial.secondaryLevel = 0;
  92656. this._groundMaterial.tertiaryLevel = 0;
  92657. this._groundMaterial.useRGBColor = false;
  92658. this._groundMaterial.enableNoise = true;
  92659. if (this._ground) {
  92660. this._ground.material = this._groundMaterial;
  92661. }
  92662. };
  92663. /**
  92664. * Setup the ground diffuse texture according to the specified options.
  92665. */
  92666. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92667. if (!this._groundMaterial) {
  92668. return;
  92669. }
  92670. if (this._groundTexture) {
  92671. return;
  92672. }
  92673. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92674. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92675. return;
  92676. }
  92677. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92678. diffuseTexture.gammaSpace = false;
  92679. diffuseTexture.hasAlpha = true;
  92680. this._groundMaterial.diffuseTexture = diffuseTexture;
  92681. };
  92682. /**
  92683. * Setup the ground mirror texture according to the specified options.
  92684. */
  92685. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92686. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92687. if (!this._groundMirror) {
  92688. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92689. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92690. this._groundMirror.anisotropicFilteringLevel = 1;
  92691. this._groundMirror.wrapU = wrapping;
  92692. this._groundMirror.wrapV = wrapping;
  92693. this._groundMirror.gammaSpace = false;
  92694. if (this._groundMirror.renderList) {
  92695. for (var i = 0; i < this._scene.meshes.length; i++) {
  92696. var mesh = this._scene.meshes[i];
  92697. if (mesh !== this._ground &&
  92698. mesh !== this._skybox &&
  92699. mesh !== this._rootMesh) {
  92700. this._groundMirror.renderList.push(mesh);
  92701. }
  92702. }
  92703. }
  92704. }
  92705. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92706. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92707. };
  92708. /**
  92709. * Setup the ground to receive the mirror texture.
  92710. */
  92711. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92712. if (this._groundMaterial) {
  92713. this._groundMaterial.reflectionTexture = this._groundMirror;
  92714. this._groundMaterial.reflectionFresnel = true;
  92715. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92716. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92717. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92718. }
  92719. };
  92720. /**
  92721. * Setup the skybox according to the specified options.
  92722. */
  92723. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92724. var _this = this;
  92725. if (!this._skybox) {
  92726. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92727. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92728. }
  92729. this._skybox.parent = this._rootMesh;
  92730. };
  92731. /**
  92732. * Setup the skybox material according to the specified options.
  92733. */
  92734. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92735. if (!this._skybox) {
  92736. return;
  92737. }
  92738. if (!this._skyboxMaterial) {
  92739. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92740. }
  92741. this._skyboxMaterial.useRGBColor = false;
  92742. this._skyboxMaterial.primaryLevel = 1;
  92743. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92744. this._skyboxMaterial.secondaryLevel = 0;
  92745. this._skyboxMaterial.tertiaryLevel = 0;
  92746. this._skyboxMaterial.enableNoise = true;
  92747. this._skybox.material = this._skyboxMaterial;
  92748. };
  92749. /**
  92750. * Setup the skybox reflection texture according to the specified options.
  92751. */
  92752. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92753. if (!this._skyboxMaterial) {
  92754. return;
  92755. }
  92756. if (this._skyboxTexture) {
  92757. return;
  92758. }
  92759. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92760. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92761. return;
  92762. }
  92763. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92764. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92765. this._skyboxTexture.gammaSpace = false;
  92766. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92767. };
  92768. /**
  92769. * Dispose all the elements created by the Helper.
  92770. */
  92771. EnvironmentHelper.prototype.dispose = function () {
  92772. if (this._groundMaterial) {
  92773. this._groundMaterial.dispose(true, true);
  92774. }
  92775. if (this._skyboxMaterial) {
  92776. this._skyboxMaterial.dispose(true, true);
  92777. }
  92778. this._rootMesh.dispose(false);
  92779. };
  92780. /**
  92781. * Default ground texture URL.
  92782. */
  92783. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92784. /**
  92785. * Default skybox texture URL.
  92786. */
  92787. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92788. /**
  92789. * Default environment texture URL.
  92790. */
  92791. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92792. return EnvironmentHelper;
  92793. }());
  92794. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92795. })(BABYLON || (BABYLON = {}));
  92796. //# sourceMappingURL=babylon.environmentHelper.js.map
  92797. "use strict";
  92798. var BABYLON;
  92799. (function (BABYLON) {
  92800. /**
  92801. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92802. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92803. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92804. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92805. */
  92806. var VideoDome = /** @class */ (function (_super) {
  92807. __extends(VideoDome, _super);
  92808. /**
  92809. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92810. * @param name Element's name, child elements will append suffixes for their own names.
  92811. * @param urlsOrVideo
  92812. * @param options An object containing optional or exposed sub element properties:
  92813. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92814. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92815. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92816. * @param options **loop=true** Automatically loop video on end.
  92817. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92818. */
  92819. function VideoDome(name, urlsOrVideo, options, scene) {
  92820. var _this = _super.call(this, name, scene) || this;
  92821. // set defaults and manage values
  92822. name = name || "videoDome";
  92823. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92824. options.clickToPlay = Boolean(options.clickToPlay);
  92825. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92826. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92827. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92828. // create
  92829. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92830. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92831. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92832. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92833. flat: false,
  92834. radius: options.size,
  92835. subdivisions: options.resolution,
  92836. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92837. }, scene);
  92838. // configure material
  92839. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92840. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92841. material.reflectionTexture = _this._videoTexture;
  92842. material.useEquirectangularFOV = true;
  92843. material.fovMultiplier = 1.0;
  92844. // configure mesh
  92845. _this._mesh.material = material;
  92846. _this._mesh.parent = _this;
  92847. // optional configuration
  92848. if (options.clickToPlay) {
  92849. scene.onPointerUp = function () {
  92850. _this._videoTexture.video.play();
  92851. };
  92852. }
  92853. return _this;
  92854. }
  92855. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92856. /**
  92857. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92858. * Also see the options.resolution property.
  92859. */
  92860. get: function () {
  92861. return this._material.fovMultiplier;
  92862. },
  92863. set: function (value) {
  92864. this._material.fovMultiplier = value;
  92865. },
  92866. enumerable: true,
  92867. configurable: true
  92868. });
  92869. /**
  92870. * Releases resources associated with this node.
  92871. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92872. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92873. */
  92874. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92875. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92876. this._videoTexture.dispose();
  92877. this._mesh.dispose();
  92878. this._material.dispose();
  92879. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92880. };
  92881. return VideoDome;
  92882. }(BABYLON.Node));
  92883. BABYLON.VideoDome = VideoDome;
  92884. })(BABYLON || (BABYLON = {}));
  92885. //# sourceMappingURL=babylon.videoDome.js.map
  92886. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  92887. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  92888. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92889. globalObject["BABYLON"] = BABYLON
  92890. return BABYLON;
  92891. });
  92892. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  92893. /***/ }),
  92894. /* 1 */
  92895. /***/ (function(module, exports, __webpack_require__) {
  92896. "use strict";
  92897. Object.defineProperty(exports, "__esModule", { value: true });
  92898. var babylonjs_1 = __webpack_require__(0);
  92899. var helper_1 = __webpack_require__(3);
  92900. var HTMLMapper = (function () {
  92901. function HTMLMapper() {
  92902. }
  92903. HTMLMapper.prototype.map = function (element) {
  92904. var config = {};
  92905. var _loop_1 = function (attrIdx) {
  92906. var attr = element.attributes.item(attrIdx);
  92907. var split = attr.nodeName.split('.');
  92908. split.reduce(function (currentConfig, key, idx) {
  92909. var camelKey = helper_1.kebabToCamel(key);
  92910. if (idx === split.length - 1) {
  92911. var val = attr.nodeValue;
  92912. if (val === "true") {
  92913. val = true;
  92914. }
  92915. else if (val === "false") {
  92916. val = false;
  92917. }
  92918. else {
  92919. var isnum = /^\d+$/.test(val);
  92920. if (isnum) {
  92921. var number = parseFloat(val);
  92922. if (!isNaN(number)) {
  92923. val = number;
  92924. }
  92925. }
  92926. }
  92927. currentConfig[camelKey] = val;
  92928. }
  92929. else {
  92930. currentConfig[camelKey] = currentConfig[camelKey] || {};
  92931. }
  92932. return currentConfig[camelKey];
  92933. }, config);
  92934. };
  92935. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  92936. _loop_1(attrIdx);
  92937. }
  92938. return config;
  92939. };
  92940. return HTMLMapper;
  92941. }());
  92942. var JSONMapper = (function () {
  92943. function JSONMapper() {
  92944. }
  92945. JSONMapper.prototype.map = function (rawSource) {
  92946. return JSON.parse(rawSource);
  92947. };
  92948. return JSONMapper;
  92949. }());
  92950. var DOMMapper = (function () {
  92951. function DOMMapper() {
  92952. }
  92953. DOMMapper.prototype.map = function (baseElement) {
  92954. var htmlMapper = new HTMLMapper();
  92955. var config = htmlMapper.map(baseElement);
  92956. var traverseChildren = function (element, partConfig) {
  92957. var children = element.children;
  92958. if (children.length) {
  92959. for (var i = 0; i < children.length; ++i) {
  92960. var item = children.item(i);
  92961. var configMapped = htmlMapper.map(item);
  92962. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  92963. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  92964. partConfig[key] = [];
  92965. }
  92966. else {
  92967. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  92968. partConfig.push(configMapped);
  92969. }
  92970. else if (partConfig[key]) {
  92971. element.setAttribute('array', 'true');
  92972. var oldItem = partConfig[key];
  92973. partConfig = [oldItem, configMapped];
  92974. }
  92975. else {
  92976. partConfig[key] = configMapped;
  92977. }
  92978. }
  92979. traverseChildren(item, partConfig[key] || configMapped);
  92980. }
  92981. }
  92982. return partConfig;
  92983. };
  92984. traverseChildren(baseElement, config);
  92985. return config;
  92986. };
  92987. return DOMMapper;
  92988. }());
  92989. var MapperManager = (function () {
  92990. function MapperManager() {
  92991. this._mappers = {
  92992. "html": new HTMLMapper(),
  92993. "json": new JSONMapper(),
  92994. "dom": new DOMMapper()
  92995. };
  92996. }
  92997. MapperManager.prototype.getMapper = function (type) {
  92998. if (!this._mappers[type]) {
  92999. babylonjs_1.Tools.Error("No mapper defined for " + type);
  93000. }
  93001. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  93002. };
  93003. MapperManager.prototype.registerMapper = function (type, mapper) {
  93004. this._mappers[type] = mapper;
  93005. };
  93006. MapperManager.prototype.dispose = function () {
  93007. this._mappers = {};
  93008. };
  93009. MapperManager.DefaultMapper = 'json';
  93010. return MapperManager;
  93011. }());
  93012. exports.MapperManager = MapperManager;
  93013. exports.mapperManager = new MapperManager();
  93014. /***/ }),
  93015. /* 2 */
  93016. /***/ (function(module, exports, __webpack_require__) {
  93017. (function (global, factory) {
  93018. true ? module.exports = factory() :
  93019. typeof define === 'function' && define.amd ? define(factory) :
  93020. (global.deepmerge = factory());
  93021. }(this, (function () { 'use strict';
  93022. var isMergeableObject = function isMergeableObject(value) {
  93023. return isNonNullObject(value)
  93024. && !isSpecial(value)
  93025. };
  93026. function isNonNullObject(value) {
  93027. return !!value && typeof value === 'object'
  93028. }
  93029. function isSpecial(value) {
  93030. var stringValue = Object.prototype.toString.call(value);
  93031. return stringValue === '[object RegExp]'
  93032. || stringValue === '[object Date]'
  93033. || isReactElement(value)
  93034. }
  93035. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  93036. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  93037. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  93038. function isReactElement(value) {
  93039. return value.$$typeof === REACT_ELEMENT_TYPE
  93040. }
  93041. function emptyTarget(val) {
  93042. return Array.isArray(val) ? [] : {}
  93043. }
  93044. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  93045. var clone = !optionsArgument || optionsArgument.clone !== false;
  93046. return (clone && isMergeableObject(value))
  93047. ? deepmerge(emptyTarget(value), value, optionsArgument)
  93048. : value
  93049. }
  93050. function defaultArrayMerge(target, source, optionsArgument) {
  93051. return target.concat(source).map(function(element) {
  93052. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  93053. })
  93054. }
  93055. function mergeObject(target, source, optionsArgument) {
  93056. var destination = {};
  93057. if (isMergeableObject(target)) {
  93058. Object.keys(target).forEach(function(key) {
  93059. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  93060. });
  93061. }
  93062. Object.keys(source).forEach(function(key) {
  93063. if (!isMergeableObject(source[key]) || !target[key]) {
  93064. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  93065. } else {
  93066. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  93067. }
  93068. });
  93069. return destination
  93070. }
  93071. function deepmerge(target, source, optionsArgument) {
  93072. var sourceIsArray = Array.isArray(source);
  93073. var targetIsArray = Array.isArray(target);
  93074. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  93075. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  93076. if (!sourceAndTargetTypesMatch) {
  93077. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  93078. } else if (sourceIsArray) {
  93079. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  93080. return arrayMerge(target, source, optionsArgument)
  93081. } else {
  93082. return mergeObject(target, source, optionsArgument)
  93083. }
  93084. }
  93085. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  93086. if (!Array.isArray(array)) {
  93087. throw new Error('first argument should be an array')
  93088. }
  93089. return array.reduce(function(prev, next) {
  93090. return deepmerge(prev, next, optionsArgument)
  93091. }, {})
  93092. };
  93093. var deepmerge_1 = deepmerge;
  93094. return deepmerge_1;
  93095. })));
  93096. /***/ }),
  93097. /* 3 */
  93098. /***/ (function(module, exports, __webpack_require__) {
  93099. "use strict";
  93100. Object.defineProperty(exports, "__esModule", { value: true });
  93101. function isUrl(urlToCheck) {
  93102. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  93103. return true;
  93104. }
  93105. return false;
  93106. }
  93107. exports.isUrl = isUrl;
  93108. function kebabToCamel(s) {
  93109. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  93110. }
  93111. exports.kebabToCamel = kebabToCamel;
  93112. function camelToKebab(str) {
  93113. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  93114. }
  93115. exports.camelToKebab = camelToKebab;
  93116. /***/ }),
  93117. /* 4 */
  93118. /***/ (function(module, exports, __webpack_require__) {
  93119. "use strict";
  93120. Object.defineProperty(exports, "__esModule", { value: true });
  93121. var babylonjs_1 = __webpack_require__(0);
  93122. var ViewerManager = (function () {
  93123. function ViewerManager() {
  93124. this._viewers = {};
  93125. this.onViewerAddedObservable = new babylonjs_1.Observable();
  93126. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  93127. }
  93128. ViewerManager.prototype.addViewer = function (viewer) {
  93129. this._viewers[viewer.getBaseId()] = viewer;
  93130. this._onViewerAdded(viewer);
  93131. };
  93132. ViewerManager.prototype.removeViewer = function (viewer) {
  93133. var id = viewer.getBaseId();
  93134. delete this._viewers[id];
  93135. this.onViewerRemovedObservable.notifyObservers(id);
  93136. };
  93137. ViewerManager.prototype.getViewerById = function (id) {
  93138. return this._viewers[id];
  93139. };
  93140. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  93141. for (var id in this._viewers) {
  93142. if (this._viewers[id].containerElement === element) {
  93143. return this.getViewerById(id);
  93144. }
  93145. }
  93146. };
  93147. ViewerManager.prototype.getViewerPromiseById = function (id) {
  93148. var _this = this;
  93149. return new Promise(function (resolve, reject) {
  93150. var localViewer = _this.getViewerById(id);
  93151. if (localViewer) {
  93152. return resolve(localViewer);
  93153. }
  93154. var viewerFunction = function (viewer) {
  93155. if (viewer.getBaseId() === id) {
  93156. resolve(viewer);
  93157. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  93158. }
  93159. };
  93160. _this.onViewerAddedObservable.add(viewerFunction);
  93161. });
  93162. };
  93163. ViewerManager.prototype._onViewerAdded = function (viewer) {
  93164. this.onViewerAdded && this.onViewerAdded(viewer);
  93165. this.onViewerAddedObservable.notifyObservers(viewer);
  93166. };
  93167. ViewerManager.prototype.dispose = function () {
  93168. for (var id in this._viewers) {
  93169. this._viewers[id].dispose();
  93170. }
  93171. };
  93172. return ViewerManager;
  93173. }());
  93174. exports.ViewerManager = ViewerManager;
  93175. exports.viewerManager = new ViewerManager();
  93176. /***/ }),
  93177. /* 5 */
  93178. /***/ (function(module, exports, __webpack_require__) {
  93179. "use strict";
  93180. var __extends = (this && this.__extends) || (function () {
  93181. var extendStatics = Object.setPrototypeOf ||
  93182. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  93183. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  93184. return function (d, b) {
  93185. extendStatics(d, b);
  93186. function __() { this.constructor = d; }
  93187. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  93188. };
  93189. })();
  93190. Object.defineProperty(exports, "__esModule", { value: true });
  93191. var viewer_1 = __webpack_require__(6);
  93192. var babylonjs_1 = __webpack_require__(0);
  93193. var DefaultViewer = (function (_super) {
  93194. __extends(DefaultViewer, _super);
  93195. function DefaultViewer(containerElement, initialConfiguration) {
  93196. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  93197. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  93198. _this.containerElement = containerElement;
  93199. _this._onModelLoaded = function (model) {
  93200. _this._configureTemplate(model);
  93201. var hideLoadingDelay = 500;
  93202. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  93203. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  93204. }
  93205. setTimeout(function () {
  93206. _this.hideLoadingScreen();
  93207. }, hideLoadingDelay);
  93208. return;
  93209. };
  93210. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  93211. return _this;
  93212. }
  93213. DefaultViewer.prototype._initScene = function () {
  93214. var _this = this;
  93215. return _super.prototype._initScene.call(this).then(function () {
  93216. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  93217. return _this.scene;
  93218. });
  93219. };
  93220. DefaultViewer.prototype._onTemplatesLoaded = function () {
  93221. var _this = this;
  93222. this.showLoadingScreen();
  93223. this._initNavbar();
  93224. var closeButton = document.getElementById('close-button');
  93225. if (closeButton) {
  93226. closeButton.addEventListener('pointerdown', function () {
  93227. _this.hideOverlayScreen();
  93228. });
  93229. }
  93230. return _super.prototype._onTemplatesLoaded.call(this);
  93231. };
  93232. DefaultViewer.prototype._initNavbar = function () {
  93233. var navbar = this.templateManager.getTemplate('navBar');
  93234. if (navbar) {
  93235. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  93236. var navbarShown_1 = true;
  93237. var timeoutCancel_1;
  93238. var triggerNavbar = function (show, evt) {
  93239. if (show === void 0) { show = false; }
  93240. if (!navbar || evt.button > 0)
  93241. return;
  93242. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  93243. if (show === navbarShown_1)
  93244. return;
  93245. if (show) {
  93246. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  93247. navbarShown_1 = show;
  93248. }
  93249. else {
  93250. var visibilityTimeout = 2000;
  93251. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  93252. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  93253. }
  93254. timeoutCancel_1 = setTimeout(function () {
  93255. if (navbar) {
  93256. navbar.parent.style.bottom = '-' + navbarHeight_1;
  93257. }
  93258. navbarShown_1 = show;
  93259. }, visibilityTimeout);
  93260. }
  93261. };
  93262. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  93263. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  93264. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  93265. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  93266. var viewerTemplate = this.templateManager.getTemplate('viewer');
  93267. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  93268. var triggerFullscren = function (eventData) {
  93269. if (viewerElement_1) {
  93270. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  93271. if (!fullscreenElement) {
  93272. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  93273. requestFullScreen.call(viewerElement_1);
  93274. }
  93275. else {
  93276. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  93277. exitFullscreen.call(document);
  93278. }
  93279. }
  93280. };
  93281. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  93282. }
  93283. };
  93284. DefaultViewer.prototype._prepareContainerElement = function () {
  93285. this.containerElement.style.position = 'relative';
  93286. this.containerElement.style.display = 'flex';
  93287. };
  93288. DefaultViewer.prototype._configureTemplate = function (model) {
  93289. var navbar = this.templateManager.getTemplate('navBar');
  93290. if (!navbar)
  93291. return;
  93292. var modelConfiguration = model.configuration;
  93293. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  93294. if (metadataContainer) {
  93295. if (modelConfiguration.title !== undefined) {
  93296. var element = metadataContainer.querySelector('span.model-title');
  93297. if (element) {
  93298. element.innerHTML = modelConfiguration.title;
  93299. }
  93300. }
  93301. if (modelConfiguration.subtitle !== undefined) {
  93302. var element = metadataContainer.querySelector('span.model-subtitle');
  93303. if (element) {
  93304. element.innerHTML = modelConfiguration.subtitle;
  93305. }
  93306. }
  93307. if (modelConfiguration.thumbnail !== undefined) {
  93308. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  93309. }
  93310. }
  93311. };
  93312. DefaultViewer.prototype.loadModel = function (model) {
  93313. var _this = this;
  93314. if (model === void 0) { model = this._configuration.model; }
  93315. this.showLoadingScreen();
  93316. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  93317. console.log(error);
  93318. _this.hideLoadingScreen();
  93319. _this.showOverlayScreen('error');
  93320. return Promise.reject(error);
  93321. });
  93322. };
  93323. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  93324. var _this = this;
  93325. var template = this.templateManager.getTemplate('overlay');
  93326. if (!template)
  93327. return Promise.resolve('Overlay template not found');
  93328. return template.show((function (template) {
  93329. var canvasRect = _this.containerElement.getBoundingClientRect();
  93330. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  93331. template.parent.style.display = 'flex';
  93332. template.parent.style.width = canvasRect.width + "px";
  93333. template.parent.style.height = canvasRect.height + "px";
  93334. template.parent.style.opacity = "1";
  93335. var subTemplate = _this.templateManager.getTemplate(subScreen);
  93336. if (!subTemplate) {
  93337. return Promise.reject(subScreen + ' template not found');
  93338. }
  93339. return subTemplate.show((function (template) {
  93340. template.parent.style.display = 'flex';
  93341. return Promise.resolve(template);
  93342. }));
  93343. }));
  93344. };
  93345. DefaultViewer.prototype.hideOverlayScreen = function () {
  93346. var template = this.templateManager.getTemplate('overlay');
  93347. if (!template)
  93348. return Promise.resolve('Overlay template not found');
  93349. return template.hide((function (template) {
  93350. template.parent.style.opacity = "0";
  93351. var onTransitionEnd = function () {
  93352. template.parent.removeEventListener("transitionend", onTransitionEnd);
  93353. template.parent.style.display = 'none';
  93354. };
  93355. template.parent.addEventListener("transitionend", onTransitionEnd);
  93356. var overlays = template.parent.querySelectorAll('.overlay');
  93357. if (overlays) {
  93358. for (var i = 0; i < overlays.length; ++i) {
  93359. var htmlElement = overlays.item(i);
  93360. htmlElement.style.display = 'none';
  93361. }
  93362. }
  93363. return Promise.resolve(template);
  93364. }));
  93365. };
  93366. DefaultViewer.prototype.showLoadingScreen = function () {
  93367. var _this = this;
  93368. var template = this.templateManager.getTemplate('loadingScreen');
  93369. if (!template)
  93370. return Promise.resolve('Loading Screen template not found');
  93371. return template.show((function (template) {
  93372. var canvasRect = _this.containerElement.getBoundingClientRect();
  93373. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  93374. template.parent.style.display = 'flex';
  93375. template.parent.style.width = canvasRect.width + "px";
  93376. template.parent.style.height = canvasRect.height + "px";
  93377. template.parent.style.opacity = "1";
  93378. template.parent.style.backgroundColor = "black";
  93379. return Promise.resolve(template);
  93380. }));
  93381. };
  93382. DefaultViewer.prototype.hideLoadingScreen = function () {
  93383. var template = this.templateManager.getTemplate('loadingScreen');
  93384. if (!template)
  93385. return Promise.resolve('Loading Screen template not found');
  93386. return template.hide((function (template) {
  93387. template.parent.style.opacity = "0";
  93388. var onTransitionEnd = function () {
  93389. template.parent.removeEventListener("transitionend", onTransitionEnd);
  93390. template.parent.style.display = 'none';
  93391. };
  93392. template.parent.addEventListener("transitionend", onTransitionEnd);
  93393. return Promise.resolve(template);
  93394. }));
  93395. };
  93396. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  93397. var _this = this;
  93398. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  93399. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  93400. if (this._configuration.lab && this._configuration.lab.flashlight) {
  93401. var pointerPosition = babylonjs_1.Vector3.Zero();
  93402. var lightTarget_1;
  93403. var angle = 0.5;
  93404. var exponent = Math.PI / 2;
  93405. if (typeof this._configuration.lab.flashlight === "object") {
  93406. exponent = this._configuration.lab.flashlight.exponent || exponent;
  93407. angle = this._configuration.lab.flashlight.angle || angle;
  93408. }
  93409. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  93410. if (typeof this._configuration.lab.flashlight === "object") {
  93411. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  93412. if (this._configuration.lab.flashlight.diffuse) {
  93413. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  93414. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  93415. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  93416. }
  93417. if (this._configuration.lab.flashlight.specular) {
  93418. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  93419. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  93420. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  93421. }
  93422. }
  93423. this.scene.constantlyUpdateMeshUnderPointer = true;
  93424. this.scene.onPointerObservable.add(function (eventData, eventState) {
  93425. if (eventData.type === 4 && eventData.pickInfo) {
  93426. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  93427. }
  93428. else {
  93429. lightTarget_1 = undefined;
  93430. }
  93431. });
  93432. var updateFlashlightFunction = function () {
  93433. if (_this.camera && flashlight) {
  93434. flashlight.position.copyFrom(_this.camera.position);
  93435. if (lightTarget_1) {
  93436. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  93437. }
  93438. }
  93439. };
  93440. this.scene.registerBeforeRender(updateFlashlightFunction);
  93441. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  93442. }
  93443. };
  93444. return DefaultViewer;
  93445. }(viewer_1.AbstractViewer));
  93446. exports.DefaultViewer = DefaultViewer;
  93447. /***/ }),
  93448. /* 6 */
  93449. /***/ (function(module, exports, __webpack_require__) {
  93450. "use strict";
  93451. Object.defineProperty(exports, "__esModule", { value: true });
  93452. var viewerManager_1 = __webpack_require__(4);
  93453. var templateManager_1 = __webpack_require__(22);
  93454. var loader_1 = __webpack_require__(25);
  93455. var babylonjs_1 = __webpack_require__(0);
  93456. var deepmerge = __webpack_require__(2);
  93457. var modelLoader_1 = __webpack_require__(14);
  93458. var AbstractViewer = (function () {
  93459. function AbstractViewer(containerElement, initialConfiguration) {
  93460. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  93461. var _this = this;
  93462. this.containerElement = containerElement;
  93463. this._isDisposed = false;
  93464. this._resize = function () {
  93465. if (!_this.isCanvasInDOM()) {
  93466. return;
  93467. }
  93468. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  93469. return;
  93470. }
  93471. _this.engine.resize();
  93472. };
  93473. this._render = function () {
  93474. _this.scene && _this.scene.activeCamera && _this.scene.render();
  93475. };
  93476. if (containerElement.id) {
  93477. this.baseId = containerElement.id;
  93478. }
  93479. else {
  93480. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  93481. }
  93482. this.onSceneInitObservable = new babylonjs_1.Observable();
  93483. this.onEngineInitObservable = new babylonjs_1.Observable();
  93484. this.onModelLoadedObservable = new babylonjs_1.Observable();
  93485. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  93486. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  93487. this.onInitDoneObservable = new babylonjs_1.Observable();
  93488. this.onLoaderInitObservable = new babylonjs_1.Observable();
  93489. this._registeredOnBeforeRenderFunctions = [];
  93490. this.models = [];
  93491. this.modelLoader = new modelLoader_1.ModelLoader(this);
  93492. viewerManager_1.viewerManager.addViewer(this);
  93493. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  93494. this._prepareContainerElement();
  93495. this._configurationLoader = new loader_1.ConfigurationLoader();
  93496. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  93497. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  93498. if (_this._configuration.observers) {
  93499. _this._configureObservers(_this._configuration.observers);
  93500. }
  93501. var templateConfiguration = _this._configuration.templates || {};
  93502. _this.templateManager.initTemplate(templateConfiguration);
  93503. _this.templateManager.onAllLoaded.add(function () {
  93504. var canvas = _this.templateManager.getCanvas();
  93505. if (canvas) {
  93506. _this._canvas = canvas;
  93507. }
  93508. _this._onTemplateLoaded();
  93509. });
  93510. });
  93511. }
  93512. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  93513. get: function () {
  93514. return this._hdrSupport;
  93515. },
  93516. enumerable: true,
  93517. configurable: true
  93518. });
  93519. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  93520. get: function () {
  93521. return this._canvas;
  93522. },
  93523. enumerable: true,
  93524. configurable: true
  93525. });
  93526. AbstractViewer.prototype.getBaseId = function () {
  93527. return this.baseId;
  93528. };
  93529. AbstractViewer.prototype.isCanvasInDOM = function () {
  93530. return !!this._canvas && !!this._canvas.parentElement;
  93531. };
  93532. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  93533. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  93534. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  93535. if (newConfiguration.scene) {
  93536. this._configureScene(newConfiguration.scene);
  93537. }
  93538. if (newConfiguration.optimizer) {
  93539. this._configureOptimizer(newConfiguration.optimizer);
  93540. }
  93541. if (newConfiguration.observers) {
  93542. this._configureObservers(newConfiguration.observers);
  93543. }
  93544. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  93545. this._configureModel(newConfiguration.model);
  93546. }
  93547. if (newConfiguration.lights) {
  93548. this._configureLights(newConfiguration.lights);
  93549. }
  93550. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  93551. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  93552. }
  93553. if (newConfiguration.camera) {
  93554. this._configureCamera(newConfiguration.camera);
  93555. }
  93556. };
  93557. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  93558. if (!skyboxConifguration && !groundConfiguration) {
  93559. if (this.environmentHelper) {
  93560. this.environmentHelper.dispose();
  93561. delete this.environmentHelper;
  93562. }
  93563. ;
  93564. return Promise.resolve(this.scene);
  93565. }
  93566. var options = {
  93567. createGround: !!groundConfiguration,
  93568. createSkybox: !!skyboxConifguration,
  93569. setupImageProcessing: false
  93570. };
  93571. if (groundConfiguration) {
  93572. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  93573. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  93574. if (groundSize) {
  93575. options.groundSize = groundSize;
  93576. }
  93577. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  93578. if (groundConfig.shadowLevel !== undefined) {
  93579. options.groundShadowLevel = groundConfig.shadowLevel;
  93580. }
  93581. options.enableGroundMirror = !!groundConfig.mirror;
  93582. if (groundConfig.texture) {
  93583. options.groundTexture = groundConfig.texture;
  93584. }
  93585. if (groundConfig.color) {
  93586. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  93587. }
  93588. if (groundConfig.opacity !== undefined) {
  93589. options.groundOpacity = groundConfig.opacity;
  93590. }
  93591. if (groundConfig.mirror) {
  93592. options.enableGroundMirror = true;
  93593. if (typeof groundConfig.mirror === "object") {
  93594. if (groundConfig.mirror.amount !== undefined)
  93595. options.groundMirrorAmount = groundConfig.mirror.amount;
  93596. if (groundConfig.mirror.sizeRatio !== undefined)
  93597. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  93598. if (groundConfig.mirror.blurKernel !== undefined)
  93599. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  93600. if (groundConfig.mirror.fresnelWeight !== undefined)
  93601. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  93602. if (groundConfig.mirror.fallOffDistance !== undefined)
  93603. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  93604. if (this._defaultPipelineTextureType !== undefined)
  93605. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  93606. }
  93607. }
  93608. }
  93609. var postInitSkyboxMaterial = false;
  93610. if (skyboxConifguration) {
  93611. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  93612. if (conf.material && conf.material.imageProcessingConfiguration) {
  93613. options.setupImageProcessing = false;
  93614. }
  93615. var skyboxSize = conf.scale;
  93616. if (skyboxSize) {
  93617. options.skyboxSize = skyboxSize;
  93618. }
  93619. options.sizeAuto = !options.skyboxSize;
  93620. if (conf.color) {
  93621. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  93622. }
  93623. if (conf.cubeTexture && conf.cubeTexture.url) {
  93624. if (typeof conf.cubeTexture.url === "string") {
  93625. options.skyboxTexture = conf.cubeTexture.url;
  93626. }
  93627. else {
  93628. postInitSkyboxMaterial = true;
  93629. }
  93630. }
  93631. if (conf.material && conf.material.imageProcessingConfiguration) {
  93632. postInitSkyboxMaterial = true;
  93633. }
  93634. }
  93635. options.setupImageProcessing = false;
  93636. if (!this.environmentHelper) {
  93637. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  93638. }
  93639. else {
  93640. var scene = this.environmentHelper.rootMesh.getScene();
  93641. if (scene !== this.scene) {
  93642. this.environmentHelper.dispose();
  93643. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  93644. }
  93645. else {
  93646. this.environmentHelper.updateOptions(options);
  93647. }
  93648. }
  93649. if (postInitSkyboxMaterial) {
  93650. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  93651. if (skyboxMaterial) {
  93652. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  93653. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  93654. }
  93655. }
  93656. }
  93657. };
  93658. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  93659. if (!this.scene) {
  93660. return;
  93661. }
  93662. if (sceneConfig.debug) {
  93663. this.scene.debugLayer.show();
  93664. }
  93665. else {
  93666. if (this.scene.debugLayer.isVisible()) {
  93667. this.scene.debugLayer.hide();
  93668. }
  93669. }
  93670. if (sceneConfig.clearColor) {
  93671. var cc = sceneConfig.clearColor;
  93672. var oldcc = this.scene.clearColor;
  93673. if (cc.r !== undefined) {
  93674. oldcc.r = cc.r;
  93675. }
  93676. if (cc.g !== undefined) {
  93677. oldcc.g = cc.g;
  93678. }
  93679. if (cc.b !== undefined) {
  93680. oldcc.b = cc.b;
  93681. }
  93682. if (cc.a !== undefined) {
  93683. oldcc.a = cc.a;
  93684. }
  93685. }
  93686. if (sceneConfig.imageProcessingConfiguration) {
  93687. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  93688. }
  93689. if (sceneConfig.environmentTexture) {
  93690. if (this.scene.environmentTexture) {
  93691. this.scene.environmentTexture.dispose();
  93692. }
  93693. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  93694. this.scene.environmentTexture = environmentTexture;
  93695. }
  93696. if (sceneConfig.autoRotate) {
  93697. this.camera.useAutoRotationBehavior = true;
  93698. }
  93699. };
  93700. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  93701. if (typeof optimizerConfig === 'boolean') {
  93702. if (this.sceneOptimizer) {
  93703. this.sceneOptimizer.stop();
  93704. this.sceneOptimizer.dispose();
  93705. delete this.sceneOptimizer;
  93706. }
  93707. if (optimizerConfig) {
  93708. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  93709. this.sceneOptimizer.start();
  93710. }
  93711. }
  93712. else {
  93713. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  93714. if (optimizerConfig.degradation) {
  93715. switch (optimizerConfig.degradation) {
  93716. case "low":
  93717. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  93718. break;
  93719. case "moderate":
  93720. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  93721. break;
  93722. case "hight":
  93723. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  93724. break;
  93725. }
  93726. }
  93727. if (this.sceneOptimizer) {
  93728. this.sceneOptimizer.stop();
  93729. this.sceneOptimizer.dispose();
  93730. }
  93731. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  93732. this.sceneOptimizer.start();
  93733. }
  93734. };
  93735. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  93736. if (observersConfiguration.onEngineInit) {
  93737. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  93738. }
  93739. else {
  93740. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  93741. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  93742. }
  93743. }
  93744. if (observersConfiguration.onSceneInit) {
  93745. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  93746. }
  93747. else {
  93748. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  93749. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  93750. }
  93751. }
  93752. if (observersConfiguration.onModelLoaded) {
  93753. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  93754. }
  93755. else {
  93756. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  93757. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  93758. }
  93759. }
  93760. };
  93761. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  93762. var _this = this;
  93763. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93764. if (!this.scene.activeCamera) {
  93765. this.scene.createDefaultCamera(true, true, true);
  93766. this.camera = this.scene.activeCamera;
  93767. }
  93768. if (cameraConfig.position) {
  93769. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  93770. }
  93771. if (cameraConfig.rotation) {
  93772. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  93773. }
  93774. this._extendClassWithConfig(this.camera, cameraConfig);
  93775. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  93776. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  93777. if (cameraConfig.behaviors) {
  93778. for (var name_1 in cameraConfig.behaviors) {
  93779. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  93780. }
  93781. }
  93782. ;
  93783. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  93784. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  93785. });
  93786. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  93787. var sceneDiagonalLenght = sceneDiagonal.length();
  93788. if (isFinite(sceneDiagonalLenght))
  93789. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  93790. };
  93791. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  93792. var _this = this;
  93793. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  93794. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93795. if (!Object.keys(lightsConfiguration).length)
  93796. return;
  93797. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  93798. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  93799. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  93800. lightsAvailable.forEach(function (lName) {
  93801. if (lightsToConfigure.indexOf(lName) === -1) {
  93802. _this.scene.getLightByName(lName).dispose();
  93803. }
  93804. });
  93805. }
  93806. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  93807. var lightConfig = { type: 0 };
  93808. if (typeof lightsConfiguration[name] === 'object') {
  93809. lightConfig = lightsConfiguration[name];
  93810. }
  93811. lightConfig.name = name;
  93812. var light;
  93813. if (lightsAvailable.indexOf(name) === -1) {
  93814. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93815. if (!constructor)
  93816. return;
  93817. light = constructor();
  93818. }
  93819. else {
  93820. light = _this.scene.getLightByName(name);
  93821. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  93822. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  93823. light.dispose();
  93824. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93825. if (!constructor)
  93826. return;
  93827. light = constructor();
  93828. }
  93829. }
  93830. if (lightsConfiguration[name] === false) {
  93831. light.dispose();
  93832. return;
  93833. }
  93834. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  93835. light.setEnabled(enabled);
  93836. _this._extendClassWithConfig(light, lightConfig);
  93837. if (light instanceof babylonjs_1.ShadowLight) {
  93838. if (lightConfig.target) {
  93839. if (light.setDirectionToTarget) {
  93840. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  93841. light.setDirectionToTarget(target);
  93842. }
  93843. }
  93844. else if (lightConfig.direction) {
  93845. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  93846. light.direction = direction;
  93847. }
  93848. var shadowGenerator = light.getShadowGenerator();
  93849. if (lightConfig.shadowEnabled && _this._maxShadows) {
  93850. if (!shadowGenerator) {
  93851. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  93852. }
  93853. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  93854. var shadownMap = shadowGenerator.getShadowMap();
  93855. if (!shadownMap)
  93856. return;
  93857. var renderList = shadownMap.renderList;
  93858. for (var index = 0; index < focusMeshes.length; index++) {
  93859. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  93860. renderList && renderList.push(focusMeshes[index]);
  93861. }
  93862. }
  93863. }
  93864. else if (shadowGenerator) {
  93865. shadowGenerator.dispose();
  93866. }
  93867. }
  93868. });
  93869. };
  93870. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  93871. this.models.forEach(function (model) {
  93872. model.updateConfiguration(modelConfiguration);
  93873. });
  93874. };
  93875. AbstractViewer.prototype.dispose = function () {
  93876. if (this._isDisposed) {
  93877. return;
  93878. }
  93879. window.removeEventListener('resize', this._resize);
  93880. if (this.sceneOptimizer) {
  93881. this.sceneOptimizer.stop();
  93882. this.sceneOptimizer.dispose();
  93883. }
  93884. if (this.environmentHelper) {
  93885. this.environmentHelper.dispose();
  93886. }
  93887. if (this._configurationLoader) {
  93888. this._configurationLoader.dispose();
  93889. }
  93890. this.onEngineInitObservable.clear();
  93891. delete this.onEngineInitObservable;
  93892. this.onInitDoneObservable.clear();
  93893. delete this.onInitDoneObservable;
  93894. this.onLoaderInitObservable.clear();
  93895. delete this.onLoaderInitObservable;
  93896. this.onModelLoadedObservable.clear();
  93897. delete this.onModelLoadedObservable;
  93898. this.onModelLoadErrorObservable.clear();
  93899. delete this.onModelLoadErrorObservable;
  93900. this.onModelLoadProgressObservable.clear();
  93901. delete this.onModelLoadProgressObservable;
  93902. this.onSceneInitObservable.clear();
  93903. delete this.onSceneInitObservable;
  93904. if (this.scene.activeCamera) {
  93905. this.scene.activeCamera.detachControl(this.canvas);
  93906. }
  93907. this.modelLoader.dispose();
  93908. this.models.forEach(function (model) {
  93909. model.dispose();
  93910. });
  93911. this.models.length = 0;
  93912. this.scene.dispose();
  93913. this.engine.dispose();
  93914. this.templateManager.dispose();
  93915. viewerManager_1.viewerManager.removeViewer(this);
  93916. this._isDisposed = true;
  93917. };
  93918. AbstractViewer.prototype._onTemplatesLoaded = function () {
  93919. return Promise.resolve(this);
  93920. };
  93921. AbstractViewer.prototype._onTemplateLoaded = function () {
  93922. var _this = this;
  93923. return this._onTemplatesLoaded().then(function () {
  93924. var autoLoadModel = _this._configuration.model;
  93925. return _this._initEngine().then(function (engine) {
  93926. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  93927. }).then(function () {
  93928. if (autoLoadModel) {
  93929. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  93930. }
  93931. else {
  93932. return _this.scene || _this._initScene();
  93933. }
  93934. }).then(function (scene) {
  93935. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  93936. }).then(function () {
  93937. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  93938. }).catch(function (e) {
  93939. babylonjs_1.Tools.Warn(e.toString());
  93940. return _this;
  93941. });
  93942. });
  93943. };
  93944. AbstractViewer.prototype._initEngine = function () {
  93945. this._injectCustomShaders();
  93946. var canvasElement = this.templateManager.getCanvas();
  93947. if (!canvasElement) {
  93948. return Promise.reject('Canvas element not found!');
  93949. }
  93950. var config = this._configuration.engine || {};
  93951. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  93952. babylonjs_1.Database.IDBStorageEnabled = false;
  93953. if (!config.disableResize) {
  93954. window.addEventListener('resize', this._resize);
  93955. }
  93956. this.engine.runRenderLoop(this._render);
  93957. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  93958. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  93959. this.engine.setHardwareScalingLevel(scale);
  93960. }
  93961. this._handleHardwareLimitations();
  93962. return Promise.resolve(this.engine);
  93963. };
  93964. AbstractViewer.prototype._initScene = function () {
  93965. if (this.scene) {
  93966. this.scene.dispose();
  93967. }
  93968. this.scene = new babylonjs_1.Scene(this.engine);
  93969. this.scene.createDefaultLight(true);
  93970. if (this._configuration.scene) {
  93971. this._configureScene(this._configuration.scene);
  93972. if (this._configuration.optimizer) {
  93973. this._configureOptimizer(this._configuration.optimizer);
  93974. }
  93975. }
  93976. return Promise.resolve(this.scene);
  93977. };
  93978. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  93979. var _this = this;
  93980. if (clearScene === void 0) { clearScene = true; }
  93981. if (clearScene) {
  93982. this.models.forEach(function (m) { return m.dispose(); });
  93983. this.models.length = 0;
  93984. }
  93985. var model = this.modelLoader.load(modelConfig);
  93986. this.lastUsedLoader = model.loader;
  93987. model.onLoadErrorObservable.add(function (errorObject) {
  93988. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  93989. });
  93990. model.onLoadProgressObservable.add(function (progressEvent) {
  93991. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93992. });
  93993. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  93994. model.onLoadedObservable.add(function () {
  93995. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  93996. .then(function () {
  93997. _this._configureLights(_this._configuration.lights);
  93998. if (_this._configuration.camera || !_this.scene.activeCamera) {
  93999. _this._configureCamera(_this._configuration.camera || {}, model);
  94000. }
  94001. return _this._initEnvironment(model);
  94002. }).then(function () {
  94003. _this._isLoading = false;
  94004. return model;
  94005. });
  94006. });
  94007. return model;
  94008. };
  94009. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  94010. var _this = this;
  94011. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  94012. if (clearScene === void 0) { clearScene = true; }
  94013. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  94014. if (!modelUrl) {
  94015. return Promise.reject("no model configuration found");
  94016. }
  94017. if (this._isLoading) {
  94018. return Promise.reject("another model is curently being loaded.");
  94019. }
  94020. this._isLoading = true;
  94021. if ((typeof modelConfig === 'string')) {
  94022. if (this._configuration.model && typeof this._configuration.model === 'object') {
  94023. this._configuration.model.url = modelConfig;
  94024. }
  94025. }
  94026. else {
  94027. if (this._configuration.model) {
  94028. deepmerge(this._configuration.model, modelConfig);
  94029. }
  94030. else {
  94031. this._configuration.model = modelConfig;
  94032. }
  94033. }
  94034. return Promise.resolve(this.scene).then(function (scene) {
  94035. if (!scene)
  94036. return _this._initScene();
  94037. return scene;
  94038. }).then(function () {
  94039. return new Promise(function (resolve, reject) {
  94040. return _this.initModel(modelConfig, clearScene);
  94041. });
  94042. });
  94043. };
  94044. AbstractViewer.prototype._initEnvironment = function (model) {
  94045. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  94046. return Promise.resolve(this.scene);
  94047. };
  94048. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  94049. if (enableHDR === void 0) { enableHDR = true; }
  94050. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  94051. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  94052. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  94053. this._maxShadows = 0;
  94054. }
  94055. else {
  94056. this._maxShadows = 3;
  94057. }
  94058. var caps = this.engine.getCaps();
  94059. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  94060. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  94061. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  94062. if (linearHalfFloatTargets) {
  94063. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  94064. this._shadowGeneratorBias = 0.002;
  94065. }
  94066. else if (linearFloatTargets) {
  94067. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  94068. this._shadowGeneratorBias = 0.001;
  94069. }
  94070. else {
  94071. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  94072. this._shadowGeneratorBias = 0.001;
  94073. }
  94074. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  94075. };
  94076. AbstractViewer.prototype._injectCustomShaders = function () {
  94077. var customShaders = this._configuration.customShaders;
  94078. if (!customShaders) {
  94079. return;
  94080. }
  94081. if (customShaders.shaders) {
  94082. Object.keys(customShaders.shaders).forEach(function (key) {
  94083. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  94084. });
  94085. }
  94086. if (customShaders.includes) {
  94087. Object.keys(customShaders.includes).forEach(function (key) {
  94088. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  94089. });
  94090. }
  94091. };
  94092. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  94093. var _this = this;
  94094. if (!config)
  94095. return;
  94096. Object.keys(config).forEach(function (key) {
  94097. if (key in object && typeof object[key] !== 'function') {
  94098. if (typeof object[key] === 'object') {
  94099. _this._extendClassWithConfig(object[key], config[key]);
  94100. }
  94101. else {
  94102. if (config[key] !== undefined) {
  94103. object[key] = config[key];
  94104. }
  94105. }
  94106. }
  94107. });
  94108. };
  94109. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  94110. var behavior;
  94111. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  94112. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  94113. switch (type) {
  94114. case 0:
  94115. this.camera.useAutoRotationBehavior = true;
  94116. behavior = this.camera.autoRotationBehavior;
  94117. break;
  94118. case 1:
  94119. this.camera.useBouncingBehavior = true;
  94120. behavior = this.camera.bouncingBehavior;
  94121. break;
  94122. case 2:
  94123. this.camera.useFramingBehavior = true;
  94124. behavior = this.camera.framingBehavior;
  94125. break;
  94126. default:
  94127. behavior = null;
  94128. break;
  94129. }
  94130. if (behavior) {
  94131. if (typeof behaviorConfig === "object") {
  94132. this._extendClassWithConfig(behavior, behaviorConfig);
  94133. }
  94134. }
  94135. switch (type) {
  94136. case 0:
  94137. break;
  94138. case 1:
  94139. break;
  94140. case 2:
  94141. if (config.zoomOnBoundingInfo) {
  94142. var meshes = payload;
  94143. var bounding = meshes[0].getHierarchyBoundingVectors();
  94144. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  94145. }
  94146. break;
  94147. }
  94148. };
  94149. return AbstractViewer;
  94150. }());
  94151. exports.AbstractViewer = AbstractViewer;
  94152. /***/ }),
  94153. /* 7 */
  94154. /***/ (function(module, exports) {
  94155. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  94156. /***/ }),
  94157. /* 8 */
  94158. /***/ (function(module, exports) {
  94159. 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}}>";
  94160. /***/ }),
  94161. /* 9 */
  94162. /***/ (function(module, exports) {
  94163. 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=="
  94164. /***/ }),
  94165. /* 10 */
  94166. /***/ (function(module, exports) {
  94167. 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>";
  94168. /***/ }),
  94169. /* 11 */
  94170. /***/ (function(module, exports) {
  94171. 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>";
  94172. /***/ }),
  94173. /* 12 */
  94174. /***/ (function(module, exports) {
  94175. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  94176. /***/ }),
  94177. /* 13 */
  94178. /***/ (function(module, exports) {
  94179. module.exports = "Error loading the model";
  94180. /***/ }),
  94181. /* 14 */
  94182. /***/ (function(module, exports, __webpack_require__) {
  94183. "use strict";
  94184. Object.defineProperty(exports, "__esModule", { value: true });
  94185. var babylonjs_1 = __webpack_require__(0);
  94186. var viewerModel_1 = __webpack_require__(15);
  94187. var ModelLoader = (function () {
  94188. function ModelLoader(_viewer) {
  94189. this._viewer = _viewer;
  94190. this._disposed = false;
  94191. this._loaders = [];
  94192. this._loadId = 0;
  94193. }
  94194. ModelLoader.prototype.load = function (modelConfiguration) {
  94195. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  94196. if (!modelConfiguration.url) {
  94197. model.state = viewerModel_1.ModelState.ERROR;
  94198. babylonjs_1.Tools.Error("No URL provided");
  94199. return model;
  94200. }
  94201. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  94202. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  94203. var plugin = modelConfiguration.loader;
  94204. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons) {
  94205. meshes.forEach(function (mesh) {
  94206. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  94207. });
  94208. model.meshes = meshes;
  94209. model.particleSystems = particleSystems;
  94210. model.skeletons = skeletons;
  94211. model.initAnimations();
  94212. model.onLoadedObservable.notifyObserversWithPromise(model);
  94213. }, function (progressEvent) {
  94214. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  94215. }, function (e, m, exception) {
  94216. model.state = viewerModel_1.ModelState.ERROR;
  94217. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  94218. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  94219. }, plugin);
  94220. if (model.loader.name === "gltf") {
  94221. var gltfLoader = model.loader;
  94222. gltfLoader.animationStartMode = 0;
  94223. gltfLoader.onAnimationGroupLoaded = function (ag) {
  94224. model.addAnimationGroup(ag);
  94225. };
  94226. }
  94227. model.loadId = this._loadId++;
  94228. this._loaders.push(model.loader);
  94229. return model;
  94230. };
  94231. ModelLoader.prototype.cancelLoad = function (model) {
  94232. var loader = model.loader || this._loaders[model.loadId];
  94233. if (loader && loader.name === "gltf") {
  94234. var gltfLoader = loader;
  94235. gltfLoader.dispose();
  94236. model.state = viewerModel_1.ModelState.CANCELED;
  94237. }
  94238. else {
  94239. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  94240. }
  94241. };
  94242. ModelLoader.prototype.dispose = function () {
  94243. this._loaders.forEach(function (loader) {
  94244. if (loader.name === "gltf") {
  94245. loader.dispose();
  94246. }
  94247. });
  94248. this._loaders.length = 0;
  94249. this._disposed = true;
  94250. };
  94251. return ModelLoader;
  94252. }());
  94253. exports.ModelLoader = ModelLoader;
  94254. /***/ }),
  94255. /* 15 */
  94256. /***/ (function(module, exports, __webpack_require__) {
  94257. "use strict";
  94258. Object.defineProperty(exports, "__esModule", { value: true });
  94259. var babylonjs_1 = __webpack_require__(0);
  94260. var modelAnimation_1 = __webpack_require__(16);
  94261. var deepmerge = __webpack_require__(2);
  94262. var ModelState;
  94263. (function (ModelState) {
  94264. ModelState[ModelState["INIT"] = 0] = "INIT";
  94265. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  94266. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  94267. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  94268. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  94269. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  94270. var ViewerModel = (function () {
  94271. function ViewerModel(_viewer, modelConfiguration) {
  94272. this._viewer = _viewer;
  94273. this.meshes = [];
  94274. this.particleSystems = [];
  94275. this.skeletons = [];
  94276. this.onLoadedObservable = new babylonjs_1.Observable();
  94277. this.onLoadErrorObservable = new babylonjs_1.Observable();
  94278. this.onLoadProgressObservable = new babylonjs_1.Observable();
  94279. this.onAfterConfigure = new babylonjs_1.Observable();
  94280. this.state = ModelState.INIT;
  94281. this._animations = [];
  94282. this._modelConfiguration = deepmerge({}, modelConfiguration);
  94283. this._viewer.models.push(this);
  94284. }
  94285. Object.defineProperty(ViewerModel.prototype, "configuration", {
  94286. get: function () {
  94287. return this._modelConfiguration;
  94288. },
  94289. set: function (newConfiguration) {
  94290. this._modelConfiguration = newConfiguration;
  94291. this._configureModel();
  94292. },
  94293. enumerable: true,
  94294. configurable: true
  94295. });
  94296. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  94297. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  94298. this._configureModel();
  94299. };
  94300. ViewerModel.prototype.initAnimations = function () {
  94301. var _this = this;
  94302. this._animations.forEach(function (a) {
  94303. a.dispose();
  94304. });
  94305. this._animations.length = 0;
  94306. if (this.loader.name !== 'gltf') {
  94307. this.skeletons.forEach(function (skeleton, idx) {
  94308. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  94309. skeleton.getAnimatables().forEach(function (a) {
  94310. if (a.animations[0]) {
  94311. ag.addTargetedAnimation(a.animations[0], a);
  94312. }
  94313. });
  94314. _this.addAnimationGroup(ag);
  94315. });
  94316. }
  94317. if (!this._modelConfiguration)
  94318. return;
  94319. if (this._modelConfiguration.animation) {
  94320. if (this._modelConfiguration.animation.playOnce) {
  94321. this._animations.forEach(function (a) {
  94322. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  94323. });
  94324. }
  94325. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  94326. var animationName = this._modelConfiguration.animation.autoStart === true ?
  94327. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  94328. this.playAnimation(animationName);
  94329. }
  94330. }
  94331. };
  94332. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  94333. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  94334. };
  94335. ViewerModel.prototype.getAnimations = function () {
  94336. return this._animations;
  94337. };
  94338. ViewerModel.prototype.getAnimationNames = function () {
  94339. return this._animations.map(function (a) { return a.name; });
  94340. };
  94341. ViewerModel.prototype._getAnimationByName = function (name) {
  94342. var filtered = this._animations.filter(function (a) { return a.name === name; });
  94343. if (filtered.length === 1) {
  94344. return filtered[0];
  94345. }
  94346. else {
  94347. return null;
  94348. }
  94349. };
  94350. ViewerModel.prototype.playAnimation = function (name) {
  94351. var animation = this._getAnimationByName(name);
  94352. if (animation) {
  94353. if (this.currentAnimation) {
  94354. this.currentAnimation.stop();
  94355. }
  94356. this.currentAnimation = animation;
  94357. animation.start();
  94358. return animation;
  94359. }
  94360. else {
  94361. throw new Error("animation not found - " + name);
  94362. }
  94363. };
  94364. ViewerModel.prototype._configureModel = function () {
  94365. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  94366. var updateMeshesWithNoParent = function (variable, value, param) {
  94367. meshesWithNoParent.forEach(function (mesh) {
  94368. if (param) {
  94369. mesh[variable][param] = value;
  94370. }
  94371. else {
  94372. mesh[variable] = value;
  94373. }
  94374. });
  94375. };
  94376. var updateXYZ = function (variable, configValues) {
  94377. if (configValues.x !== undefined) {
  94378. updateMeshesWithNoParent(variable, configValues.x, 'x');
  94379. }
  94380. if (configValues.y !== undefined) {
  94381. updateMeshesWithNoParent(variable, configValues.y, 'y');
  94382. }
  94383. if (configValues.z !== undefined) {
  94384. updateMeshesWithNoParent(variable, configValues.z, 'z');
  94385. }
  94386. if (configValues.w !== undefined) {
  94387. updateMeshesWithNoParent(variable, configValues.w, 'w');
  94388. }
  94389. };
  94390. if (this._modelConfiguration.position) {
  94391. updateXYZ('position', this._modelConfiguration.position);
  94392. }
  94393. if (this._modelConfiguration.rotation) {
  94394. if (this._modelConfiguration.rotation.w) {
  94395. meshesWithNoParent.forEach(function (mesh) {
  94396. if (!mesh.rotationQuaternion) {
  94397. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  94398. }
  94399. });
  94400. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  94401. }
  94402. else {
  94403. updateXYZ('rotation', this._modelConfiguration.rotation);
  94404. }
  94405. }
  94406. if (this._modelConfiguration.scaling) {
  94407. updateXYZ('scaling', this._modelConfiguration.scaling);
  94408. }
  94409. if (this._modelConfiguration.castShadow) {
  94410. this.meshes.forEach(function (mesh) {
  94411. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  94412. });
  94413. }
  94414. if (this._modelConfiguration.normalize) {
  94415. var center = false;
  94416. var unitSize = false;
  94417. var parentIndex = void 0;
  94418. if (this._modelConfiguration.normalize === true) {
  94419. center = true;
  94420. unitSize = true;
  94421. parentIndex = 0;
  94422. }
  94423. else {
  94424. center = !!this._modelConfiguration.normalize.center;
  94425. unitSize = !!this._modelConfiguration.normalize.unitSize;
  94426. parentIndex = this._modelConfiguration.normalize.parentIndex;
  94427. }
  94428. var meshesToNormalize = [];
  94429. if (parentIndex !== undefined) {
  94430. meshesToNormalize.push(this.meshes[parentIndex]);
  94431. }
  94432. else {
  94433. meshesToNormalize = meshesWithNoParent;
  94434. }
  94435. if (unitSize) {
  94436. meshesToNormalize.forEach(function (mesh) {
  94437. mesh.normalizeToUnitCube(true);
  94438. mesh.computeWorldMatrix(true);
  94439. });
  94440. }
  94441. if (center) {
  94442. meshesToNormalize.forEach(function (mesh) {
  94443. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  94444. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  94445. var halfSizeVec = sizeVec.scale(0.5);
  94446. var center = boundingInfo.min.add(halfSizeVec);
  94447. mesh.position = center.scale(-1);
  94448. mesh.position.y += halfSizeVec.y;
  94449. mesh.computeWorldMatrix(true);
  94450. });
  94451. }
  94452. }
  94453. this.onAfterConfigure.notifyObservers(this);
  94454. };
  94455. ViewerModel.prototype.dispose = function () {
  94456. this.onAfterConfigure.clear();
  94457. this.onLoadedObservable.clear();
  94458. this.onLoadErrorObservable.clear();
  94459. this.onLoadProgressObservable.clear();
  94460. if (this.loader && this.loader.name === "gltf") {
  94461. this.loader.dispose();
  94462. }
  94463. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  94464. this.particleSystems.length = 0;
  94465. this.skeletons.forEach(function (s) { return s.dispose(); });
  94466. this.skeletons.length = 0;
  94467. this._animations.forEach(function (ag) { return ag.dispose(); });
  94468. this._animations.length = 0;
  94469. this.meshes.forEach(function (m) { return m.dispose(); });
  94470. this.meshes.length = 0;
  94471. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  94472. };
  94473. return ViewerModel;
  94474. }());
  94475. exports.ViewerModel = ViewerModel;
  94476. /***/ }),
  94477. /* 16 */
  94478. /***/ (function(module, exports, __webpack_require__) {
  94479. "use strict";
  94480. Object.defineProperty(exports, "__esModule", { value: true });
  94481. var AnimationPlayMode;
  94482. (function (AnimationPlayMode) {
  94483. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  94484. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  94485. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  94486. var AnimationState;
  94487. (function (AnimationState) {
  94488. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  94489. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  94490. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  94491. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  94492. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  94493. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  94494. var GroupModelAnimation = (function () {
  94495. function GroupModelAnimation(_animationGroup) {
  94496. var _this = this;
  94497. this._animationGroup = _animationGroup;
  94498. this._state = AnimationState.INIT;
  94499. this._playMode = AnimationPlayMode.LOOP;
  94500. this._animationGroup.onAnimationEndObservable.add(function () {
  94501. _this.stop();
  94502. _this._state = AnimationState.ENDED;
  94503. });
  94504. }
  94505. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  94506. get: function () {
  94507. return this._animationGroup.name;
  94508. },
  94509. enumerable: true,
  94510. configurable: true
  94511. });
  94512. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  94513. get: function () {
  94514. return this._state;
  94515. },
  94516. enumerable: true,
  94517. configurable: true
  94518. });
  94519. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  94520. get: function () {
  94521. return this._animationGroup.speedRatio;
  94522. },
  94523. set: function (value) {
  94524. this._animationGroup.speedRatio = value;
  94525. },
  94526. enumerable: true,
  94527. configurable: true
  94528. });
  94529. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  94530. get: function () {
  94531. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  94532. var keys = ta.animation.getKeys();
  94533. return keys[keys.length - 1].frame;
  94534. });
  94535. return Math.max.apply(null, animationFrames);
  94536. },
  94537. enumerable: true,
  94538. configurable: true
  94539. });
  94540. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  94541. get: function () {
  94542. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  94543. var animatable = this._animationGroup.animatables[i];
  94544. var animations = animatable.getAnimations();
  94545. if (!animations || !animations.length) {
  94546. continue;
  94547. }
  94548. for (var idx = 0; idx < animations.length; ++idx) {
  94549. if (animations[idx].currentFrame) {
  94550. return animations[idx].currentFrame;
  94551. }
  94552. }
  94553. }
  94554. return 0;
  94555. },
  94556. enumerable: true,
  94557. configurable: true
  94558. });
  94559. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  94560. get: function () {
  94561. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  94562. var animatable = this._animationGroup.animatables[i];
  94563. var animations = animatable.getAnimations();
  94564. if (!animations || !animations.length) {
  94565. continue;
  94566. }
  94567. for (var idx = 0; idx < animations.length; ++idx) {
  94568. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  94569. return animations[idx].animation.framePerSecond;
  94570. }
  94571. }
  94572. }
  94573. return 0;
  94574. },
  94575. enumerable: true,
  94576. configurable: true
  94577. });
  94578. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  94579. get: function () {
  94580. return this._playMode;
  94581. },
  94582. set: function (value) {
  94583. if (value === this._playMode) {
  94584. return;
  94585. }
  94586. this._playMode = value;
  94587. if (this.state === AnimationState.PLAYING) {
  94588. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  94589. }
  94590. else {
  94591. this._animationGroup.reset();
  94592. this._state = AnimationState.INIT;
  94593. }
  94594. },
  94595. enumerable: true,
  94596. configurable: true
  94597. });
  94598. GroupModelAnimation.prototype.reset = function () {
  94599. this._animationGroup.reset();
  94600. };
  94601. GroupModelAnimation.prototype.restart = function () {
  94602. this._animationGroup.restart();
  94603. };
  94604. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  94605. this._animationGroup['_animatables'].forEach(function (a) {
  94606. a.goToFrame(frameNumber);
  94607. });
  94608. };
  94609. GroupModelAnimation.prototype.start = function () {
  94610. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  94611. if (this._animationGroup.isStarted) {
  94612. this._state = AnimationState.PLAYING;
  94613. }
  94614. };
  94615. GroupModelAnimation.prototype.pause = function () {
  94616. this._animationGroup.pause();
  94617. this._state = AnimationState.PAUSED;
  94618. };
  94619. GroupModelAnimation.prototype.stop = function () {
  94620. this._animationGroup.stop();
  94621. if (!this._animationGroup.isStarted) {
  94622. this._state = AnimationState.STOPPED;
  94623. }
  94624. };
  94625. GroupModelAnimation.prototype.dispose = function () {
  94626. this._animationGroup.dispose();
  94627. };
  94628. return GroupModelAnimation;
  94629. }());
  94630. exports.GroupModelAnimation = GroupModelAnimation;
  94631. /***/ }),
  94632. /* 17 */
  94633. /***/ (function(module, exports, __webpack_require__) {
  94634. module.exports = __webpack_require__(18);
  94635. /***/ }),
  94636. /* 18 */
  94637. /***/ (function(module, exports, __webpack_require__) {
  94638. "use strict";
  94639. Object.defineProperty(exports, "__esModule", { value: true });
  94640. var mappers_1 = __webpack_require__(1);
  94641. exports.mapperManager = mappers_1.mapperManager;
  94642. var viewerManager_1 = __webpack_require__(4);
  94643. exports.viewerManager = viewerManager_1.viewerManager;
  94644. var defaultViewer_1 = __webpack_require__(5);
  94645. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  94646. var viewer_1 = __webpack_require__(6);
  94647. exports.AbstractViewer = viewer_1.AbstractViewer;
  94648. var modelLoader_1 = __webpack_require__(14);
  94649. exports.ModelLoader = modelLoader_1.ModelLoader;
  94650. var viewerModel_1 = __webpack_require__(15);
  94651. exports.ViewerModel = viewerModel_1.ViewerModel;
  94652. exports.ModelState = viewerModel_1.ModelState;
  94653. var modelAnimation_1 = __webpack_require__(16);
  94654. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  94655. exports.AnimationState = modelAnimation_1.AnimationState;
  94656. var babylonjs_1 = __webpack_require__(0);
  94657. __webpack_require__(33);
  94658. __webpack_require__(34);
  94659. var initializer_1 = __webpack_require__(35);
  94660. exports.InitTags = initializer_1.InitTags;
  94661. babylonjs_1.PromisePolyfill.Apply();
  94662. exports.disableInit = false;
  94663. document.addEventListener("DOMContentLoaded", init);
  94664. function init(event) {
  94665. document.removeEventListener("DOMContentLoaded", init);
  94666. if (exports.disableInit)
  94667. return;
  94668. initializer_1.InitTags();
  94669. }
  94670. function disposeAll() {
  94671. viewerManager_1.viewerManager.dispose();
  94672. mappers_1.mapperManager.dispose();
  94673. }
  94674. exports.disposeAll = disposeAll;
  94675. /***/ }),
  94676. /* 19 */
  94677. /***/ (function(module, exports) {
  94678. var g;
  94679. // This works in non-strict mode
  94680. g = (function() {
  94681. return this;
  94682. })();
  94683. try {
  94684. // This works if eval is allowed (see CSP)
  94685. g = g || Function("return this")() || (1,eval)("this");
  94686. } catch(e) {
  94687. // This works if the window reference is available
  94688. if(typeof window === "object")
  94689. g = window;
  94690. }
  94691. // g can still be undefined, but nothing to do about it...
  94692. // We return undefined, instead of nothing here, so it's
  94693. // easier to handle this case. if(!global) { ...}
  94694. module.exports = g;
  94695. /***/ }),
  94696. /* 20 */
  94697. /***/ (function(module, exports) {
  94698. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94699. module.exports = CANNON;
  94700. /***/ }),
  94701. /* 21 */
  94702. /***/ (function(module, exports) {
  94703. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94704. module.exports = OIMO;
  94705. /***/ }),
  94706. /* 22 */
  94707. /***/ (function(module, exports, __webpack_require__) {
  94708. "use strict";
  94709. Object.defineProperty(exports, "__esModule", { value: true });
  94710. var babylonjs_1 = __webpack_require__(0);
  94711. var helper_1 = __webpack_require__(3);
  94712. var TemplateManager = (function () {
  94713. function TemplateManager(containerElement) {
  94714. this.containerElement = containerElement;
  94715. this.templates = {};
  94716. this.onTemplateInit = new babylonjs_1.Observable();
  94717. this.onTemplateLoaded = new babylonjs_1.Observable();
  94718. this.onTemplateStateChange = new babylonjs_1.Observable();
  94719. this.onAllLoaded = new babylonjs_1.Observable();
  94720. this.onEventTriggered = new babylonjs_1.Observable();
  94721. this.eventManager = new eventManager_1.EventManager(this);
  94722. }
  94723. TemplateManager.prototype.initTemplate = function (templates) {
  94724. var _this = this;
  94725. var internalInit = function (dependencyMap, name, parentTemplate) {
  94726. var template = _this.templates[name];
  94727. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  94728. return internalInit(dependencyMap[childName], childName, template);
  94729. });
  94730. var addToParent = function () {
  94731. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  94732. template.appendTo(containingElement);
  94733. _this._checkLoadedState();
  94734. };
  94735. if (parentTemplate && !parentTemplate.parent) {
  94736. parentTemplate.onAppended.add(function () {
  94737. addToParent();
  94738. });
  94739. }
  94740. else {
  94741. addToParent();
  94742. }
  94743. return template;
  94744. };
  94745. return this._buildHTMLTree(templates).then(function (htmlTree) {
  94746. if (_this.templates['main']) {
  94747. internalInit(htmlTree, 'main');
  94748. }
  94749. else {
  94750. _this._checkLoadedState();
  94751. }
  94752. return;
  94753. });
  94754. };
  94755. TemplateManager.prototype._buildHTMLTree = function (templates) {
  94756. var _this = this;
  94757. var promises = Object.keys(templates).map(function (name) {
  94758. if (!templates[name])
  94759. return Promise.resolve(false);
  94760. var template = new Template(name, templates[name]);
  94761. template.onLoaded.add(function () {
  94762. _this.onTemplateLoaded.notifyObservers(template);
  94763. });
  94764. template.onStateChange.add(function () {
  94765. _this.onTemplateStateChange.notifyObservers(template);
  94766. });
  94767. _this.onTemplateInit.notifyObservers(template);
  94768. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  94769. _this.templates[name] = template;
  94770. return template.initPromise;
  94771. });
  94772. return Promise.all(promises).then(function () {
  94773. var templateStructure = {};
  94774. var buildTree = function (parentObject, name) {
  94775. _this.templates[name].isInHtmlTree = true;
  94776. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  94777. childNodes.forEach(function (element) {
  94778. parentObject[element] = {};
  94779. buildTree(parentObject[element], element);
  94780. });
  94781. };
  94782. if (_this.templates['main']) {
  94783. buildTree(templateStructure, "main");
  94784. }
  94785. return templateStructure;
  94786. });
  94787. };
  94788. TemplateManager.prototype.getCanvas = function () {
  94789. return this.containerElement.querySelector('canvas');
  94790. };
  94791. TemplateManager.prototype.getTemplate = function (name) {
  94792. return this.templates[name];
  94793. };
  94794. TemplateManager.prototype._checkLoadedState = function () {
  94795. var _this = this;
  94796. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  94797. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  94798. });
  94799. if (done) {
  94800. this.onAllLoaded.notifyObservers(this);
  94801. }
  94802. };
  94803. TemplateManager.prototype.dispose = function () {
  94804. var _this = this;
  94805. Object.keys(this.templates).forEach(function (template) {
  94806. _this.templates[template].dispose();
  94807. });
  94808. this.templates = {};
  94809. this.eventManager.dispose();
  94810. this.onTemplateInit.clear();
  94811. this.onAllLoaded.clear();
  94812. this.onEventTriggered.clear();
  94813. this.onTemplateLoaded.clear();
  94814. this.onTemplateStateChange.clear();
  94815. };
  94816. return TemplateManager;
  94817. }());
  94818. exports.TemplateManager = TemplateManager;
  94819. var Handlebars = __webpack_require__(23);
  94820. var eventManager_1 = __webpack_require__(24);
  94821. Handlebars.registerHelper('eachInMap', function (map, block) {
  94822. var out = '';
  94823. Object.keys(map).map(function (prop) {
  94824. var data = map[prop];
  94825. if (typeof data === 'object') {
  94826. data.id = data.id || prop;
  94827. out += block.fn(data);
  94828. }
  94829. else {
  94830. out += block.fn({ id: prop, value: data });
  94831. }
  94832. });
  94833. return out;
  94834. });
  94835. var Template = (function () {
  94836. function Template(name, _configuration) {
  94837. var _this = this;
  94838. this.name = name;
  94839. this._configuration = _configuration;
  94840. this.onLoaded = new babylonjs_1.Observable();
  94841. this.onAppended = new babylonjs_1.Observable();
  94842. this.onStateChange = new babylonjs_1.Observable();
  94843. this.onEventTriggered = new babylonjs_1.Observable();
  94844. this.loadRequests = [];
  94845. this.isLoaded = false;
  94846. this.isShown = false;
  94847. this.isInHtmlTree = false;
  94848. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  94849. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  94850. if (htmlTemplate) {
  94851. _this._htmlTemplate = htmlTemplate;
  94852. var compiledTemplate = Handlebars.compile(htmlTemplate);
  94853. var config = _this._configuration.params || {};
  94854. var rawHtml = compiledTemplate(config);
  94855. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  94856. _this.isLoaded = true;
  94857. _this.isShown = true;
  94858. _this.onLoaded.notifyObservers(_this);
  94859. }
  94860. return _this;
  94861. });
  94862. }
  94863. Template.prototype.updateParams = function (params) {
  94864. this._configuration.params = params;
  94865. if (this.isLoaded) {
  94866. this.dispose();
  94867. }
  94868. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  94869. var config = this._configuration.params || {};
  94870. var rawHtml = compiledTemplate(config);
  94871. this._fragment = document.createRange().createContextualFragment(rawHtml);
  94872. if (this.parent) {
  94873. this.appendTo(this.parent, true);
  94874. }
  94875. };
  94876. Object.defineProperty(Template.prototype, "configuration", {
  94877. get: function () {
  94878. return this._configuration;
  94879. },
  94880. enumerable: true,
  94881. configurable: true
  94882. });
  94883. Template.prototype.getChildElements = function () {
  94884. var childrenArray = [];
  94885. var children = this._fragment.children;
  94886. if (!children) {
  94887. children = this._fragment.querySelectorAll('*');
  94888. }
  94889. for (var i = 0; i < children.length; ++i) {
  94890. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  94891. }
  94892. return childrenArray;
  94893. };
  94894. Template.prototype.appendTo = function (parent, forceRemove) {
  94895. var _this = this;
  94896. if (this.parent) {
  94897. if (forceRemove) {
  94898. this.parent.removeChild(this._fragment);
  94899. }
  94900. else {
  94901. return;
  94902. }
  94903. }
  94904. this.parent = parent;
  94905. if (this._configuration.id) {
  94906. this.parent.id = this._configuration.id;
  94907. }
  94908. this._fragment = this.parent.appendChild(this._fragment);
  94909. setTimeout(function () {
  94910. _this._registerEvents();
  94911. _this.onAppended.notifyObservers(_this);
  94912. });
  94913. };
  94914. Template.prototype.show = function (visibilityFunction) {
  94915. var _this = this;
  94916. if (this._isHiding)
  94917. return Promise.resolve(this);
  94918. return Promise.resolve().then(function () {
  94919. _this._isShowing = true;
  94920. if (visibilityFunction) {
  94921. return visibilityFunction(_this);
  94922. }
  94923. else {
  94924. _this.parent.style.display = 'flex';
  94925. return _this;
  94926. }
  94927. }).then(function () {
  94928. _this.isShown = true;
  94929. _this._isShowing = false;
  94930. _this.onStateChange.notifyObservers(_this);
  94931. return _this;
  94932. });
  94933. };
  94934. Template.prototype.hide = function (visibilityFunction) {
  94935. var _this = this;
  94936. if (this._isShowing)
  94937. return Promise.resolve(this);
  94938. return Promise.resolve().then(function () {
  94939. _this._isHiding = true;
  94940. if (visibilityFunction) {
  94941. return visibilityFunction(_this);
  94942. }
  94943. else {
  94944. _this.parent.style.display = 'hide';
  94945. return _this;
  94946. }
  94947. }).then(function () {
  94948. _this.isShown = false;
  94949. _this._isHiding = false;
  94950. _this.onStateChange.notifyObservers(_this);
  94951. return _this;
  94952. });
  94953. };
  94954. Template.prototype.dispose = function () {
  94955. this.onAppended.clear();
  94956. this.onEventTriggered.clear();
  94957. this.onLoaded.clear();
  94958. this.onStateChange.clear();
  94959. this.isLoaded = false;
  94960. try {
  94961. this.parent.removeChild(this._fragment);
  94962. }
  94963. catch (e) {
  94964. }
  94965. this.loadRequests.forEach(function (request) {
  94966. request.abort();
  94967. });
  94968. if (this._registeredEvents) {
  94969. this._registeredEvents.forEach(function (evt) {
  94970. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  94971. });
  94972. }
  94973. delete this._fragment;
  94974. };
  94975. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  94976. var _this = this;
  94977. if (!templateConfig) {
  94978. return Promise.reject('No templateConfig provided');
  94979. }
  94980. else if (templateConfig.html !== undefined) {
  94981. return Promise.resolve(templateConfig.html);
  94982. }
  94983. else {
  94984. var location_1 = this._getTemplateLocation(templateConfig);
  94985. if (helper_1.isUrl(location_1)) {
  94986. return new Promise(function (resolve, reject) {
  94987. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  94988. resolve(data);
  94989. }, undefined, undefined, false, function (request, error) {
  94990. reject(error);
  94991. });
  94992. _this.loadRequests.push(fileRequest);
  94993. });
  94994. }
  94995. else {
  94996. location_1 = location_1.replace('#', '');
  94997. var element = document.getElementById(location_1);
  94998. if (element) {
  94999. return Promise.resolve(element.innerHTML);
  95000. }
  95001. else {
  95002. return Promise.reject('Template ID not found');
  95003. }
  95004. }
  95005. }
  95006. };
  95007. Template.prototype._registerEvents = function () {
  95008. var _this = this;
  95009. this._registeredEvents = this._registeredEvents || [];
  95010. if (this._registeredEvents.length) {
  95011. this._registeredEvents.forEach(function (evt) {
  95012. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  95013. });
  95014. }
  95015. if (this._configuration.events) {
  95016. var _loop_1 = function (eventName) {
  95017. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  95018. var functionToFire_1 = function (selector, event) {
  95019. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  95020. };
  95021. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  95022. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  95023. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  95024. this_1._registeredEvents.push({
  95025. htmlElement: this_1.parent,
  95026. eventName: eventName,
  95027. function: binding
  95028. });
  95029. }
  95030. else if (typeof this_1._configuration.events[eventName] === 'object') {
  95031. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  95032. var event_1 = this_1._configuration.events[eventName] || {};
  95033. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  95034. if (selector && selector.indexOf('#') !== 0) {
  95035. selector = '#' + selector;
  95036. }
  95037. var htmlElement = _this.parent.querySelector(selector);
  95038. if (htmlElement) {
  95039. var binding = functionToFire_1.bind(_this, selector);
  95040. htmlElement.addEventListener(eventName, binding, false);
  95041. _this._registeredEvents.push({
  95042. htmlElement: htmlElement,
  95043. eventName: eventName,
  95044. function: binding
  95045. });
  95046. }
  95047. });
  95048. }
  95049. }
  95050. };
  95051. var this_1 = this;
  95052. for (var eventName in this._configuration.events) {
  95053. _loop_1(eventName);
  95054. }
  95055. }
  95056. };
  95057. Template.prototype._getTemplateLocation = function (templateConfig) {
  95058. if (!templateConfig || typeof templateConfig === 'string') {
  95059. return templateConfig;
  95060. }
  95061. else {
  95062. return templateConfig.location;
  95063. }
  95064. };
  95065. return Template;
  95066. }());
  95067. exports.Template = Template;
  95068. /***/ }),
  95069. /* 23 */
  95070. /***/ (function(module, exports, __webpack_require__) {
  95071. /**!
  95072. @license
  95073. handlebars v4.0.11
  95074. Copyright (C) 2011-2017 by Yehuda Katz
  95075. Permission is hereby granted, free of charge, to any person obtaining a copy
  95076. of this software and associated documentation files (the "Software"), to deal
  95077. in the Software without restriction, including without limitation the rights
  95078. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  95079. copies of the Software, and to permit persons to whom the Software is
  95080. furnished to do so, subject to the following conditions:
  95081. The above copyright notice and this permission notice shall be included in
  95082. all copies or substantial portions of the Software.
  95083. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  95084. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  95085. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  95086. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  95087. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  95088. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  95089. THE SOFTWARE.
  95090. */
  95091. !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],
  95092. 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){
  95093. 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"]}])});
  95094. /***/ }),
  95095. /* 24 */
  95096. /***/ (function(module, exports, __webpack_require__) {
  95097. "use strict";
  95098. Object.defineProperty(exports, "__esModule", { value: true });
  95099. var EventManager = (function () {
  95100. function EventManager(_templateManager) {
  95101. var _this = this;
  95102. this._templateManager = _templateManager;
  95103. this._callbacksContainer = {};
  95104. this._templateManager.onEventTriggered.add(function (eventData) {
  95105. _this._eventTriggered(eventData);
  95106. });
  95107. }
  95108. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  95109. if (!this._callbacksContainer[templateName]) {
  95110. this._callbacksContainer[templateName] = [];
  95111. }
  95112. this._callbacksContainer[templateName].push({
  95113. eventType: eventType,
  95114. callback: callback
  95115. });
  95116. };
  95117. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  95118. var callbackDefs = this._callbacksContainer[templateName] || [];
  95119. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  95120. };
  95121. EventManager.prototype._eventTriggered = function (data) {
  95122. var templateName = data.template.name;
  95123. var eventType = data.event.type;
  95124. var selector = data.selector;
  95125. var callbackDefs = this._callbacksContainer[templateName] || [];
  95126. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  95127. callbackDef.callback(data);
  95128. });
  95129. };
  95130. EventManager.prototype.dispose = function () {
  95131. this._callbacksContainer = {};
  95132. };
  95133. return EventManager;
  95134. }());
  95135. exports.EventManager = EventManager;
  95136. /***/ }),
  95137. /* 25 */
  95138. /***/ (function(module, exports, __webpack_require__) {
  95139. "use strict";
  95140. Object.defineProperty(exports, "__esModule", { value: true });
  95141. var mappers_1 = __webpack_require__(1);
  95142. var types_1 = __webpack_require__(26);
  95143. var deepmerge = __webpack_require__(2);
  95144. var babylonjs_1 = __webpack_require__(0);
  95145. var ConfigurationLoader = (function () {
  95146. function ConfigurationLoader(_enableCache) {
  95147. if (_enableCache === void 0) { _enableCache = false; }
  95148. this._enableCache = _enableCache;
  95149. this._configurationCache = {};
  95150. this._loadRequests = [];
  95151. }
  95152. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  95153. var _this = this;
  95154. if (initConfig === void 0) { initConfig = {}; }
  95155. var loadedConfig = deepmerge({}, initConfig);
  95156. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  95157. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  95158. if (loadedConfig.configuration) {
  95159. var mapperType_1 = "json";
  95160. return Promise.resolve().then(function () {
  95161. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  95162. var url = '';
  95163. if (typeof loadedConfig.configuration === "string") {
  95164. url = loadedConfig.configuration;
  95165. }
  95166. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  95167. url = loadedConfig.configuration.url;
  95168. var type = loadedConfig.configuration.mapper;
  95169. if (!type) {
  95170. type = loadedConfig.configuration.url.split('.').pop();
  95171. }
  95172. mapperType_1 = type || mapperType_1;
  95173. }
  95174. return _this._loadFile(url);
  95175. }
  95176. else {
  95177. if (typeof loadedConfig.configuration === "object") {
  95178. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  95179. return loadedConfig.configuration.payload || {};
  95180. }
  95181. return {};
  95182. }
  95183. }).then(function (data) {
  95184. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  95185. var parsed = mapper.map(data);
  95186. var merged = deepmerge(loadedConfig, parsed);
  95187. if (callback)
  95188. callback(merged);
  95189. return merged;
  95190. });
  95191. }
  95192. else {
  95193. if (callback)
  95194. callback(loadedConfig);
  95195. return Promise.resolve(loadedConfig);
  95196. }
  95197. };
  95198. ConfigurationLoader.prototype.dispose = function () {
  95199. this._loadRequests.forEach(function (request) {
  95200. request.abort();
  95201. });
  95202. this._loadRequests.length = 0;
  95203. };
  95204. ConfigurationLoader.prototype._loadFile = function (url) {
  95205. var _this = this;
  95206. var cacheReference = this._configurationCache;
  95207. if (this._enableCache && cacheReference[url]) {
  95208. return Promise.resolve(cacheReference[url]);
  95209. }
  95210. return new Promise(function (resolve, reject) {
  95211. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  95212. var idx = _this._loadRequests.indexOf(fileRequest);
  95213. if (idx !== -1)
  95214. _this._loadRequests.splice(idx, 1);
  95215. if (_this._enableCache)
  95216. cacheReference[url] = result;
  95217. resolve(result);
  95218. }, undefined, undefined, false, function (request, error) {
  95219. var idx = _this._loadRequests.indexOf(fileRequest);
  95220. if (idx !== -1)
  95221. _this._loadRequests.splice(idx, 1);
  95222. reject(error);
  95223. });
  95224. _this._loadRequests.push(fileRequest);
  95225. });
  95226. };
  95227. return ConfigurationLoader;
  95228. }());
  95229. exports.ConfigurationLoader = ConfigurationLoader;
  95230. /***/ }),
  95231. /* 26 */
  95232. /***/ (function(module, exports, __webpack_require__) {
  95233. "use strict";
  95234. Object.defineProperty(exports, "__esModule", { value: true });
  95235. var minimal_1 = __webpack_require__(27);
  95236. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  95237. var default_1 = __webpack_require__(28);
  95238. exports.defaultConfiguration = default_1.defaultConfiguration;
  95239. var getConfigurationType = function (type) {
  95240. switch (type) {
  95241. case 'default':
  95242. return default_1.defaultConfiguration;
  95243. case 'minimal':
  95244. return minimal_1.minimalConfiguration;
  95245. case 'none':
  95246. return {};
  95247. default:
  95248. return default_1.defaultConfiguration;
  95249. }
  95250. };
  95251. exports.getConfigurationType = getConfigurationType;
  95252. /***/ }),
  95253. /* 27 */
  95254. /***/ (function(module, exports, __webpack_require__) {
  95255. "use strict";
  95256. Object.defineProperty(exports, "__esModule", { value: true });
  95257. exports.minimalConfiguration = {
  95258. version: "0.1",
  95259. templates: {
  95260. main: {
  95261. html: __webpack_require__(7)
  95262. },
  95263. loadingScreen: {
  95264. html: __webpack_require__(8),
  95265. params: {
  95266. backgroundColor: "#000000",
  95267. loadingImage: __webpack_require__(9)
  95268. }
  95269. },
  95270. viewer: {
  95271. html: __webpack_require__(10),
  95272. },
  95273. overlay: {
  95274. html: __webpack_require__(11),
  95275. params: {
  95276. closeImage: __webpack_require__(12),
  95277. closeText: 'Close'
  95278. }
  95279. },
  95280. error: {
  95281. html: __webpack_require__(13)
  95282. }
  95283. },
  95284. engine: {
  95285. antialiasing: true
  95286. }
  95287. };
  95288. /***/ }),
  95289. /* 28 */
  95290. /***/ (function(module, exports, __webpack_require__) {
  95291. "use strict";
  95292. Object.defineProperty(exports, "__esModule", { value: true });
  95293. exports.defaultConfiguration = {
  95294. version: "3.2.0-alpha4",
  95295. templates: {
  95296. main: {
  95297. html: __webpack_require__(7)
  95298. },
  95299. loadingScreen: {
  95300. html: __webpack_require__(8),
  95301. params: {
  95302. backgroundColor: "#000000",
  95303. loadingImage: __webpack_require__(9)
  95304. }
  95305. },
  95306. viewer: {
  95307. html: __webpack_require__(10),
  95308. events: {
  95309. pointerout: true,
  95310. pointerdown: true,
  95311. pointerup: true
  95312. }
  95313. },
  95314. navBar: {
  95315. html: __webpack_require__(29),
  95316. params: {
  95317. buttons: {
  95318. "fullscreen-button": {
  95319. altText: "Fullscreen",
  95320. image: __webpack_require__(30)
  95321. }
  95322. },
  95323. visibilityTimeout: 2000
  95324. },
  95325. events: {
  95326. pointerdown: { 'fullscreen-button': true },
  95327. pointerover: true
  95328. }
  95329. },
  95330. overlay: {
  95331. html: __webpack_require__(11),
  95332. params: {
  95333. closeImage: __webpack_require__(12),
  95334. closeText: 'Close'
  95335. }
  95336. },
  95337. help: {
  95338. html: __webpack_require__(31)
  95339. },
  95340. share: {
  95341. html: __webpack_require__(32)
  95342. },
  95343. error: {
  95344. html: __webpack_require__(13)
  95345. }
  95346. },
  95347. camera: {
  95348. behaviors: {
  95349. autoRotate: 0,
  95350. framing: {
  95351. type: 2,
  95352. zoomOnBoundingInfo: true,
  95353. zoomStopsAnimation: false
  95354. }
  95355. }
  95356. },
  95357. skybox: {
  95358. pbr: true,
  95359. blur: 0.7,
  95360. infiniteDIstance: false,
  95361. },
  95362. ground: true,
  95363. engine: {
  95364. antialiasing: true
  95365. },
  95366. scene: {
  95367. imageProcessingConfiguration: {
  95368. exposure: 1.4,
  95369. contrast: 1.66,
  95370. toneMappingEnabled: true
  95371. }
  95372. }
  95373. };
  95374. /***/ }),
  95375. /* 29 */
  95376. /***/ (function(module, exports) {
  95377. 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>";
  95378. /***/ }),
  95379. /* 30 */
  95380. /***/ (function(module, exports) {
  95381. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  95382. /***/ }),
  95383. /* 31 */
  95384. /***/ (function(module, exports) {
  95385. module.exports = "HELP";
  95386. /***/ }),
  95387. /* 32 */
  95388. /***/ (function(module, exports) {
  95389. module.exports = "SHARE";
  95390. /***/ }),
  95391. /* 33 */
  95392. /***/ (function(module, exports, __webpack_require__) {
  95393. 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};
  95394. 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)}}();
  95395. (function universalModuleDefinition(root, factory) {
  95396. var amdDependencies = [];
  95397. var BABYLON = root.BABYLON;
  95398. if(true) {
  95399. BABYLON = BABYLON || __webpack_require__(0);
  95400. module.exports = factory(BABYLON);
  95401. } else if(typeof define === 'function' && define.amd) {
  95402. amdDependencies.push("babylonjs");
  95403. define("babylonjs-loaders", amdDependencies, factory);
  95404. } else if(typeof exports === 'object') {
  95405. BABYLON = BABYLON || require("babylonjs");
  95406. exports["babylonjs-loaders"] = factory(BABYLON);
  95407. } else {
  95408. root["BABYLON"] = factory(BABYLON);
  95409. }
  95410. })(this, function(BABYLON) {
  95411. BABYLON = BABYLON || this.BABYLON;
  95412. "use strict";
  95413. var BABYLON;
  95414. (function (BABYLON) {
  95415. var STLFileLoader = /** @class */ (function () {
  95416. function STLFileLoader() {
  95417. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  95418. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  95419. 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;
  95420. 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;
  95421. this.name = "stl";
  95422. // force data to come in as an ArrayBuffer
  95423. // we'll convert to string if it looks like it's an ASCII .stl
  95424. this.extensions = {
  95425. ".stl": { isBinary: true },
  95426. };
  95427. }
  95428. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  95429. var matches;
  95430. if (this.isBinary(data)) {
  95431. // binary .stl
  95432. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  95433. this.parseBinary(babylonMesh, data);
  95434. if (meshes) {
  95435. meshes.push(babylonMesh);
  95436. }
  95437. return true;
  95438. }
  95439. // ASCII .stl
  95440. // convert to string
  95441. var array_buffer = new Uint8Array(data);
  95442. var str = '';
  95443. for (var i = 0; i < data.byteLength; i++) {
  95444. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  95445. }
  95446. data = str;
  95447. while (matches = this.solidPattern.exec(data)) {
  95448. var meshName = matches[1];
  95449. var meshNameFromEnd = matches[3];
  95450. if (meshName != meshNameFromEnd) {
  95451. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  95452. return false;
  95453. }
  95454. // check meshesNames
  95455. if (meshesNames && meshName) {
  95456. if (meshesNames instanceof Array) {
  95457. if (!meshesNames.indexOf(meshName)) {
  95458. continue;
  95459. }
  95460. }
  95461. else {
  95462. if (meshName !== meshesNames) {
  95463. continue;
  95464. }
  95465. }
  95466. }
  95467. // stl mesh name can be empty as well
  95468. meshName = meshName || "stlmesh";
  95469. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  95470. this.parseASCII(babylonMesh, matches[2]);
  95471. if (meshes) {
  95472. meshes.push(babylonMesh);
  95473. }
  95474. }
  95475. return true;
  95476. };
  95477. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  95478. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  95479. if (result) {
  95480. scene.createDefaultCameraOrLight();
  95481. }
  95482. return result;
  95483. };
  95484. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  95485. var container = new BABYLON.AssetContainer(scene);
  95486. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  95487. container.removeAllFromScene();
  95488. return container;
  95489. };
  95490. STLFileLoader.prototype.isBinary = function (data) {
  95491. // check if file size is correct for binary stl
  95492. var faceSize, nFaces, reader;
  95493. reader = new DataView(data);
  95494. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  95495. nFaces = reader.getUint32(80, true);
  95496. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  95497. return true;
  95498. }
  95499. // check characters higher than ASCII to confirm binary
  95500. var fileLength = reader.byteLength;
  95501. for (var index = 0; index < fileLength; index++) {
  95502. if (reader.getUint8(index) > 127) {
  95503. return true;
  95504. }
  95505. }
  95506. return false;
  95507. };
  95508. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  95509. var reader = new DataView(data);
  95510. var faces = reader.getUint32(80, true);
  95511. var dataOffset = 84;
  95512. var faceLength = 12 * 4 + 2;
  95513. var offset = 0;
  95514. var positions = new Float32Array(faces * 3 * 3);
  95515. var normals = new Float32Array(faces * 3 * 3);
  95516. var indices = new Uint32Array(faces * 3);
  95517. var indicesCount = 0;
  95518. for (var face = 0; face < faces; face++) {
  95519. var start = dataOffset + face * faceLength;
  95520. var normalX = reader.getFloat32(start, true);
  95521. var normalY = reader.getFloat32(start + 4, true);
  95522. var normalZ = reader.getFloat32(start + 8, true);
  95523. for (var i = 1; i <= 3; i++) {
  95524. var vertexstart = start + i * 12;
  95525. // ordering is intentional to match ascii import
  95526. positions[offset] = reader.getFloat32(vertexstart, true);
  95527. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  95528. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  95529. normals[offset] = normalX;
  95530. normals[offset + 2] = normalY;
  95531. normals[offset + 1] = normalZ;
  95532. offset += 3;
  95533. }
  95534. indices[indicesCount] = indicesCount++;
  95535. indices[indicesCount] = indicesCount++;
  95536. indices[indicesCount] = indicesCount++;
  95537. }
  95538. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  95539. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95540. mesh.setIndices(indices);
  95541. mesh.computeWorldMatrix(true);
  95542. };
  95543. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  95544. var positions = [];
  95545. var normals = [];
  95546. var indices = [];
  95547. var indicesCount = 0;
  95548. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  95549. var matches;
  95550. while (matches = this.facetsPattern.exec(solidData)) {
  95551. var facet = matches[1];
  95552. //one normal per face
  95553. var normalMatches = this.normalPattern.exec(facet);
  95554. this.normalPattern.lastIndex = 0;
  95555. if (!normalMatches) {
  95556. continue;
  95557. }
  95558. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  95559. var vertexMatch;
  95560. while (vertexMatch = this.vertexPattern.exec(facet)) {
  95561. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  95562. normals.push(normal[0], normal[1], normal[2]);
  95563. }
  95564. indices.push(indicesCount++, indicesCount++, indicesCount++);
  95565. this.vertexPattern.lastIndex = 0;
  95566. }
  95567. this.facetsPattern.lastIndex = 0;
  95568. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  95569. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95570. mesh.setIndices(indices);
  95571. mesh.computeWorldMatrix(true);
  95572. };
  95573. return STLFileLoader;
  95574. }());
  95575. BABYLON.STLFileLoader = STLFileLoader;
  95576. if (BABYLON.SceneLoader) {
  95577. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  95578. }
  95579. })(BABYLON || (BABYLON = {}));
  95580. //# sourceMappingURL=babylon.stlFileLoader.js.map
  95581. "use strict";
  95582. var BABYLON;
  95583. (function (BABYLON) {
  95584. /**
  95585. * Class reading and parsing the MTL file bundled with the obj file.
  95586. */
  95587. var MTLFileLoader = /** @class */ (function () {
  95588. function MTLFileLoader() {
  95589. // All material loaded from the mtl will be set here
  95590. this.materials = [];
  95591. }
  95592. /**
  95593. * This function will read the mtl file and create each material described inside
  95594. * This function could be improve by adding :
  95595. * -some component missing (Ni, Tf...)
  95596. * -including the specific options available
  95597. *
  95598. * @param scene
  95599. * @param data
  95600. * @param rootUrl
  95601. */
  95602. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  95603. if (data instanceof ArrayBuffer) {
  95604. return;
  95605. }
  95606. //Split the lines from the file
  95607. var lines = data.split('\n');
  95608. //Space char
  95609. var delimiter_pattern = /\s+/;
  95610. //Array with RGB colors
  95611. var color;
  95612. //New material
  95613. var material = null;
  95614. //Look at each line
  95615. for (var i = 0; i < lines.length; i++) {
  95616. var line = lines[i].trim();
  95617. // Blank line or comment
  95618. if (line.length === 0 || line.charAt(0) === '#') {
  95619. continue;
  95620. }
  95621. //Get the first parameter (keyword)
  95622. var pos = line.indexOf(' ');
  95623. var key = (pos >= 0) ? line.substring(0, pos) : line;
  95624. key = key.toLowerCase();
  95625. //Get the data following the key
  95626. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  95627. //This mtl keyword will create the new material
  95628. if (key === "newmtl") {
  95629. //Check if it is the first material.
  95630. // Materials specifications are described after this keyword.
  95631. if (material) {
  95632. //Add the previous material in the material array.
  95633. this.materials.push(material);
  95634. }
  95635. //Create a new material.
  95636. // value is the name of the material read in the mtl file
  95637. material = new BABYLON.StandardMaterial(value, scene);
  95638. }
  95639. else if (key === "kd" && material) {
  95640. // Diffuse color (color under white light) using RGB values
  95641. //value = "r g b"
  95642. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95643. //color = [r,g,b]
  95644. //Set tghe color into the material
  95645. material.diffuseColor = BABYLON.Color3.FromArray(color);
  95646. }
  95647. else if (key === "ka" && material) {
  95648. // Ambient color (color under shadow) using RGB values
  95649. //value = "r g b"
  95650. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95651. //color = [r,g,b]
  95652. //Set tghe color into the material
  95653. material.ambientColor = BABYLON.Color3.FromArray(color);
  95654. }
  95655. else if (key === "ks" && material) {
  95656. // Specular color (color when light is reflected from shiny surface) using RGB values
  95657. //value = "r g b"
  95658. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95659. //color = [r,g,b]
  95660. //Set the color into the material
  95661. material.specularColor = BABYLON.Color3.FromArray(color);
  95662. }
  95663. else if (key === "ke" && material) {
  95664. // Emissive color using RGB values
  95665. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95666. material.emissiveColor = BABYLON.Color3.FromArray(color);
  95667. }
  95668. else if (key === "ns" && material) {
  95669. //value = "Integer"
  95670. material.specularPower = parseFloat(value);
  95671. }
  95672. else if (key === "d" && material) {
  95673. //d is dissolve for current material. It mean alpha for BABYLON
  95674. material.alpha = parseFloat(value);
  95675. //Texture
  95676. //This part can be improved by adding the possible options of texture
  95677. }
  95678. else if (key === "map_ka" && material) {
  95679. // ambient texture map with a loaded image
  95680. //We must first get the folder of the image
  95681. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95682. }
  95683. else if (key === "map_kd" && material) {
  95684. // Diffuse texture map with a loaded image
  95685. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95686. }
  95687. else if (key === "map_ks" && material) {
  95688. // Specular texture map with a loaded image
  95689. //We must first get the folder of the image
  95690. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95691. }
  95692. else if (key === "map_ns") {
  95693. //Specular
  95694. //Specular highlight component
  95695. //We must first get the folder of the image
  95696. //
  95697. //Not supported by BABYLON
  95698. //
  95699. // continue;
  95700. }
  95701. else if (key === "map_bump" && material) {
  95702. //The bump texture
  95703. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95704. }
  95705. else if (key === "map_d" && material) {
  95706. // The dissolve of the material
  95707. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95708. //Options for illumination
  95709. }
  95710. else if (key === "illum") {
  95711. //Illumination
  95712. if (value === "0") {
  95713. //That mean Kd == Kd
  95714. }
  95715. else if (value === "1") {
  95716. //Color on and Ambient on
  95717. }
  95718. else if (value === "2") {
  95719. //Highlight on
  95720. }
  95721. else if (value === "3") {
  95722. //Reflection on and Ray trace on
  95723. }
  95724. else if (value === "4") {
  95725. //Transparency: Glass on, Reflection: Ray trace on
  95726. }
  95727. else if (value === "5") {
  95728. //Reflection: Fresnel on and Ray trace on
  95729. }
  95730. else if (value === "6") {
  95731. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  95732. }
  95733. else if (value === "7") {
  95734. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  95735. }
  95736. else if (value === "8") {
  95737. //Reflection on and Ray trace off
  95738. }
  95739. else if (value === "9") {
  95740. //Transparency: Glass on, Reflection: Ray trace off
  95741. }
  95742. else if (value === "10") {
  95743. //Casts shadows onto invisible surfaces
  95744. }
  95745. }
  95746. else {
  95747. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  95748. }
  95749. }
  95750. //At the end of the file, add the last material
  95751. if (material) {
  95752. this.materials.push(material);
  95753. }
  95754. };
  95755. /**
  95756. * Gets the texture for the material.
  95757. *
  95758. * If the material is imported from input file,
  95759. * We sanitize the url to ensure it takes the textre from aside the material.
  95760. *
  95761. * @param rootUrl The root url to load from
  95762. * @param value The value stored in the mtl
  95763. * @return The Texture
  95764. */
  95765. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  95766. if (!value) {
  95767. return null;
  95768. }
  95769. var url = rootUrl;
  95770. // Load from input file.
  95771. if (rootUrl === "file:") {
  95772. var lastDelimiter = value.lastIndexOf("\\");
  95773. if (lastDelimiter === -1) {
  95774. lastDelimiter = value.lastIndexOf("/");
  95775. }
  95776. if (lastDelimiter > -1) {
  95777. url += value.substr(lastDelimiter + 1);
  95778. }
  95779. else {
  95780. url += value;
  95781. }
  95782. }
  95783. else {
  95784. url += value;
  95785. }
  95786. return new BABYLON.Texture(url, scene);
  95787. };
  95788. return MTLFileLoader;
  95789. }());
  95790. BABYLON.MTLFileLoader = MTLFileLoader;
  95791. var OBJFileLoader = /** @class */ (function () {
  95792. function OBJFileLoader() {
  95793. this.name = "obj";
  95794. this.extensions = ".obj";
  95795. this.obj = /^o/;
  95796. this.group = /^g/;
  95797. this.mtllib = /^mtllib /;
  95798. this.usemtl = /^usemtl /;
  95799. this.smooth = /^s /;
  95800. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95801. // vn float float float
  95802. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95803. // vt float float
  95804. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95805. // f vertex vertex vertex ...
  95806. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  95807. // f vertex/uvs vertex/uvs vertex/uvs ...
  95808. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  95809. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  95810. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  95811. // f vertex//normal vertex//normal vertex//normal ...
  95812. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  95813. }
  95814. /**
  95815. * Calls synchronously the MTL file attached to this obj.
  95816. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  95817. * Without this function materials are not displayed in the first frame (but displayed after).
  95818. * In consequence it is impossible to get material information in your HTML file
  95819. *
  95820. * @param url The URL of the MTL file
  95821. * @param rootUrl
  95822. * @param onSuccess Callback function to be called when the MTL file is loaded
  95823. * @private
  95824. */
  95825. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  95826. //The complete path to the mtl file
  95827. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  95828. // Loads through the babylon tools to allow fileInput search.
  95829. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  95830. };
  95831. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  95832. //get the meshes from OBJ file
  95833. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  95834. //Push meshes from OBJ file into the variable mesh of this function
  95835. if (meshes) {
  95836. loadedMeshes.forEach(function (mesh) {
  95837. meshes.push(mesh);
  95838. });
  95839. }
  95840. return true;
  95841. };
  95842. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  95843. //Get the 3D model
  95844. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  95845. };
  95846. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  95847. var container = new BABYLON.AssetContainer(scene);
  95848. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  95849. container.removeAllFromScene();
  95850. return container;
  95851. };
  95852. /**
  95853. * Read the OBJ file and create an Array of meshes.
  95854. * Each mesh contains all information given by the OBJ and the MTL file.
  95855. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  95856. *
  95857. * @param meshesNames
  95858. * @param scene BABYLON.Scene The scene where are displayed the data
  95859. * @param data String The content of the obj file
  95860. * @param rootUrl String The path to the folder
  95861. * @returns Array<AbstractMesh>
  95862. * @private
  95863. */
  95864. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  95865. var positions = []; //values for the positions of vertices
  95866. var normals = []; //Values for the normals
  95867. var uvs = []; //Values for the textures
  95868. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  95869. var handledMesh; //The current mesh of meshes array
  95870. var indicesForBabylon = []; //The list of indices for VertexData
  95871. var wrappedPositionForBabylon = []; //The list of position in vectors
  95872. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  95873. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  95874. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  95875. var curPositionInIndices = 0;
  95876. var hasMeshes = false; //Meshes are defined in the file
  95877. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  95878. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  95879. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  95880. var triangles = []; //Indices from new triangles coming from polygons
  95881. var materialNameFromObj = ""; //The name of the current material
  95882. var fileToLoad = ""; //The name of the mtlFile to load
  95883. var materialsFromMTLFile = new MTLFileLoader();
  95884. var objMeshName = ""; //The name of the current obj mesh
  95885. var increment = 1; //Id for meshes created by the multimaterial
  95886. var isFirstMaterial = true;
  95887. /**
  95888. * Search for obj in the given array.
  95889. * This function is called to check if a couple of data already exists in an array.
  95890. *
  95891. * If found, returns the index of the founded tuple index. Returns -1 if not found
  95892. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  95893. * @param obj Array<number>
  95894. * @returns {boolean}
  95895. */
  95896. var isInArray = function (arr, obj) {
  95897. if (!arr[obj[0]])
  95898. arr[obj[0]] = { normals: [], idx: [] };
  95899. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  95900. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  95901. };
  95902. var isInArrayUV = function (arr, obj) {
  95903. if (!arr[obj[0]])
  95904. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  95905. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  95906. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  95907. return arr[obj[0]].idx[idx];
  95908. }
  95909. return -1;
  95910. };
  95911. /**
  95912. * This function set the data for each triangle.
  95913. * Data are position, normals and uvs
  95914. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  95915. * If the tuple already exist, add only their indice
  95916. *
  95917. * @param indicePositionFromObj Integer The index in positions array
  95918. * @param indiceUvsFromObj Integer The index in uvs array
  95919. * @param indiceNormalFromObj Integer The index in normals array
  95920. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  95921. * @param textureVectorFromOBJ Vector3 The value of uvs
  95922. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  95923. */
  95924. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  95925. //Check if this tuple already exists in the list of tuples
  95926. var _index;
  95927. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  95928. _index = isInArrayUV(tuplePosNorm, [
  95929. indicePositionFromObj,
  95930. indiceNormalFromObj,
  95931. indiceUvsFromObj
  95932. ]);
  95933. }
  95934. else {
  95935. _index = isInArray(tuplePosNorm, [
  95936. indicePositionFromObj,
  95937. indiceNormalFromObj
  95938. ]);
  95939. }
  95940. //If it not exists
  95941. if (_index == -1) {
  95942. //Add an new indice.
  95943. //The array of indices is only an array with his length equal to the number of triangles - 1.
  95944. //We add vertices data in this order
  95945. indicesForBabylon.push(wrappedPositionForBabylon.length);
  95946. //Push the position of vertice for Babylon
  95947. //Each element is a BABYLON.Vector3(x,y,z)
  95948. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  95949. //Push the uvs for Babylon
  95950. //Each element is a BABYLON.Vector3(u,v)
  95951. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  95952. //Push the normals for Babylon
  95953. //Each element is a BABYLON.Vector3(x,y,z)
  95954. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  95955. //Add the tuple in the comparison list
  95956. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  95957. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  95958. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  95959. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  95960. }
  95961. else {
  95962. //The tuple already exists
  95963. //Add the index of the already existing tuple
  95964. //At this index we can get the value of position, normal and uvs of vertex
  95965. indicesForBabylon.push(_index);
  95966. }
  95967. };
  95968. /**
  95969. * Transform BABYLON.Vector() object onto 3 digits in an array
  95970. */
  95971. var unwrapData = function () {
  95972. //Every array has the same length
  95973. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  95974. //Push the x, y, z values of each element in the unwrapped array
  95975. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  95976. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  95977. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  95978. }
  95979. // Reset arrays for the next new meshes
  95980. wrappedPositionForBabylon = [];
  95981. wrappedNormalsForBabylon = [];
  95982. wrappedUvsForBabylon = [];
  95983. tuplePosNorm = [];
  95984. curPositionInIndices = 0;
  95985. };
  95986. /**
  95987. * Create triangles from polygons by recursion
  95988. * The best to understand how it works is to draw it in the same time you get the recursion.
  95989. * It is important to notice that a triangle is a polygon
  95990. * We get 4 patterns of face defined in OBJ File :
  95991. * facePattern1 = ["1","2","3","4","5","6"]
  95992. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  95993. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  95994. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  95995. * Each pattern is divided by the same method
  95996. * @param face Array[String] The indices of elements
  95997. * @param v Integer The variable to increment
  95998. */
  95999. var getTriangles = function (face, v) {
  96000. //Work for each element of the array
  96001. if (v + 1 < face.length) {
  96002. //Add on the triangle variable the indexes to obtain triangles
  96003. triangles.push(face[0], face[v], face[v + 1]);
  96004. //Incrementation for recursion
  96005. v += 1;
  96006. //Recursion
  96007. getTriangles(face, v);
  96008. }
  96009. //Result obtained after 2 iterations:
  96010. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  96011. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  96012. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  96013. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  96014. };
  96015. /**
  96016. * Create triangles and push the data for each polygon for the pattern 1
  96017. * In this pattern we get vertice positions
  96018. * @param face
  96019. * @param v
  96020. */
  96021. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  96022. //Get the indices of triangles for each polygon
  96023. getTriangles(face, v);
  96024. //For each element in the triangles array.
  96025. //This var could contains 1 to an infinity of triangles
  96026. for (var k = 0; k < triangles.length; k++) {
  96027. // Set position indice
  96028. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  96029. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  96030. positions[indicePositionFromObj], //Get the vectors data
  96031. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  96032. );
  96033. }
  96034. //Reset variable for the next line
  96035. triangles = [];
  96036. };
  96037. /**
  96038. * Create triangles and push the data for each polygon for the pattern 2
  96039. * In this pattern we get vertice positions and uvsu
  96040. * @param face
  96041. * @param v
  96042. */
  96043. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  96044. //Get the indices of triangles for each polygon
  96045. getTriangles(face, v);
  96046. for (var k = 0; k < triangles.length; k++) {
  96047. //triangle[k] = "1/1"
  96048. //Split the data for getting position and uv
  96049. var point = triangles[k].split("/"); // ["1", "1"]
  96050. //Set position indice
  96051. var indicePositionFromObj = parseInt(point[0]) - 1;
  96052. //Set uv indice
  96053. var indiceUvsFromObj = parseInt(point[1]) - 1;
  96054. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  96055. positions[indicePositionFromObj], //Get the values for each element
  96056. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  96057. );
  96058. }
  96059. //Reset variable for the next line
  96060. triangles = [];
  96061. };
  96062. /**
  96063. * Create triangles and push the data for each polygon for the pattern 3
  96064. * In this pattern we get vertice positions, uvs and normals
  96065. * @param face
  96066. * @param v
  96067. */
  96068. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  96069. //Get the indices of triangles for each polygon
  96070. getTriangles(face, v);
  96071. for (var k = 0; k < triangles.length; k++) {
  96072. //triangle[k] = "1/1/1"
  96073. //Split the data for getting position, uv, and normals
  96074. var point = triangles[k].split("/"); // ["1", "1", "1"]
  96075. // Set position indice
  96076. var indicePositionFromObj = parseInt(point[0]) - 1;
  96077. // Set uv indice
  96078. var indiceUvsFromObj = parseInt(point[1]) - 1;
  96079. // Set normal indice
  96080. var indiceNormalFromObj = parseInt(point[2]) - 1;
  96081. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  96082. );
  96083. }
  96084. //Reset variable for the next line
  96085. triangles = [];
  96086. };
  96087. /**
  96088. * Create triangles and push the data for each polygon for the pattern 4
  96089. * In this pattern we get vertice positions and normals
  96090. * @param face
  96091. * @param v
  96092. */
  96093. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  96094. getTriangles(face, v);
  96095. for (var k = 0; k < triangles.length; k++) {
  96096. //triangle[k] = "1//1"
  96097. //Split the data for getting position and normals
  96098. var point = triangles[k].split("//"); // ["1", "1"]
  96099. // We check indices, and normals
  96100. var indicePositionFromObj = parseInt(point[0]) - 1;
  96101. var indiceNormalFromObj = parseInt(point[1]) - 1;
  96102. setData(indicePositionFromObj, 1, //Default value for uv
  96103. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  96104. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  96105. }
  96106. //Reset variable for the next line
  96107. triangles = [];
  96108. };
  96109. var addPreviousObjMesh = function () {
  96110. //Check if it is not the first mesh. Otherwise we don't have data.
  96111. if (meshesFromObj.length > 0) {
  96112. //Get the previous mesh for applying the data about the faces
  96113. //=> in obj file, faces definition append after the name of the mesh
  96114. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  96115. //Set the data into Array for the mesh
  96116. unwrapData();
  96117. // Reverse tab. Otherwise face are displayed in the wrong sens
  96118. indicesForBabylon.reverse();
  96119. //Set the information for the mesh
  96120. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  96121. handledMesh.indices = indicesForBabylon.slice();
  96122. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  96123. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  96124. handledMesh.uvs = unwrappedUVForBabylon.slice();
  96125. //Reset the array for the next mesh
  96126. indicesForBabylon = [];
  96127. unwrappedPositionsForBabylon = [];
  96128. unwrappedNormalsForBabylon = [];
  96129. unwrappedUVForBabylon = [];
  96130. }
  96131. };
  96132. //Main function
  96133. //Split the file into lines
  96134. var lines = data.split('\n');
  96135. //Look at each line
  96136. for (var i = 0; i < lines.length; i++) {
  96137. var line = lines[i].trim();
  96138. var result;
  96139. //Comment or newLine
  96140. if (line.length === 0 || line.charAt(0) === '#') {
  96141. continue;
  96142. //Get information about one position possible for the vertices
  96143. }
  96144. else if ((result = this.vertexPattern.exec(line)) !== null) {
  96145. //Create a Vector3 with the position x, y, z
  96146. //Value of result:
  96147. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  96148. //Add the Vector in the list of positions
  96149. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  96150. }
  96151. else if ((result = this.normalPattern.exec(line)) !== null) {
  96152. //Create a Vector3 with the normals x, y, z
  96153. //Value of result
  96154. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  96155. //Add the Vector in the list of normals
  96156. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  96157. }
  96158. else if ((result = this.uvPattern.exec(line)) !== null) {
  96159. //Create a Vector2 with the normals u, v
  96160. //Value of result
  96161. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  96162. //Add the Vector in the list of uvs
  96163. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  96164. //Identify patterns of faces
  96165. //Face could be defined in different type of pattern
  96166. }
  96167. else if ((result = this.facePattern3.exec(line)) !== null) {
  96168. //Value of result:
  96169. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  96170. //Set the data for this face
  96171. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  96172. 1);
  96173. }
  96174. else if ((result = this.facePattern4.exec(line)) !== null) {
  96175. //Value of result:
  96176. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  96177. //Set the data for this face
  96178. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  96179. 1);
  96180. }
  96181. else if ((result = this.facePattern2.exec(line)) !== null) {
  96182. //Value of result:
  96183. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  96184. //Set the data for this face
  96185. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  96186. 1);
  96187. }
  96188. else if ((result = this.facePattern1.exec(line)) !== null) {
  96189. //Value of result
  96190. //["f 1 2 3", "1 2 3"...]
  96191. //Set the data for this face
  96192. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  96193. 1);
  96194. //Define a mesh or an object
  96195. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  96196. }
  96197. else if (this.group.test(line) || this.obj.test(line)) {
  96198. //Create a new mesh corresponding to the name of the group.
  96199. //Definition of the mesh
  96200. var objMesh =
  96201. //Set the name of the current obj mesh
  96202. {
  96203. name: line.substring(2).trim(),
  96204. indices: undefined,
  96205. positions: undefined,
  96206. normals: undefined,
  96207. uvs: undefined,
  96208. materialName: ""
  96209. };
  96210. addPreviousObjMesh();
  96211. //Push the last mesh created with only the name
  96212. meshesFromObj.push(objMesh);
  96213. //Set this variable to indicate that now meshesFromObj has objects defined inside
  96214. hasMeshes = true;
  96215. isFirstMaterial = true;
  96216. increment = 1;
  96217. //Keyword for applying a material
  96218. }
  96219. else if (this.usemtl.test(line)) {
  96220. //Get the name of the material
  96221. materialNameFromObj = line.substring(7).trim();
  96222. //If this new material is in the same mesh
  96223. if (!isFirstMaterial) {
  96224. //Set the data for the previous mesh
  96225. addPreviousObjMesh();
  96226. //Create a new mesh
  96227. var objMesh =
  96228. //Set the name of the current obj mesh
  96229. {
  96230. name: objMeshName + "_mm" + increment.toString(),
  96231. indices: undefined,
  96232. positions: undefined,
  96233. normals: undefined,
  96234. uvs: undefined,
  96235. materialName: materialNameFromObj
  96236. };
  96237. increment++;
  96238. //If meshes are already defined
  96239. meshesFromObj.push(objMesh);
  96240. }
  96241. //Set the material name if the previous line define a mesh
  96242. if (hasMeshes && isFirstMaterial) {
  96243. //Set the material name to the previous mesh (1 material per mesh)
  96244. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  96245. isFirstMaterial = false;
  96246. }
  96247. //Keyword for loading the mtl file
  96248. }
  96249. else if (this.mtllib.test(line)) {
  96250. //Get the name of mtl file
  96251. fileToLoad = line.substring(7).trim();
  96252. //Apply smoothing
  96253. }
  96254. else if (this.smooth.test(line)) {
  96255. // smooth shading => apply smoothing
  96256. //Toda y I don't know it work with babylon and with obj.
  96257. //With the obj file an integer is set
  96258. }
  96259. else {
  96260. //If there is another possibility
  96261. console.log("Unhandled expression at line : " + line);
  96262. }
  96263. }
  96264. //At the end of the file, add the last mesh into the meshesFromObj array
  96265. if (hasMeshes) {
  96266. //Set the data for the last mesh
  96267. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  96268. //Reverse indices for displaying faces in the good sens
  96269. indicesForBabylon.reverse();
  96270. //Get the good array
  96271. unwrapData();
  96272. //Set array
  96273. handledMesh.indices = indicesForBabylon;
  96274. handledMesh.positions = unwrappedPositionsForBabylon;
  96275. handledMesh.normals = unwrappedNormalsForBabylon;
  96276. handledMesh.uvs = unwrappedUVForBabylon;
  96277. }
  96278. //If any o or g keyword found, create a mesj with a random id
  96279. if (!hasMeshes) {
  96280. // reverse tab of indices
  96281. indicesForBabylon.reverse();
  96282. //Get positions normals uvs
  96283. unwrapData();
  96284. //Set data for one mesh
  96285. meshesFromObj.push({
  96286. name: BABYLON.Geometry.RandomId(),
  96287. indices: indicesForBabylon,
  96288. positions: unwrappedPositionsForBabylon,
  96289. normals: unwrappedNormalsForBabylon,
  96290. uvs: unwrappedUVForBabylon,
  96291. materialName: materialNameFromObj
  96292. });
  96293. }
  96294. //Create a BABYLON.Mesh list
  96295. var babylonMeshesArray = []; //The mesh for babylon
  96296. var materialToUse = new Array();
  96297. //Set data for each mesh
  96298. for (var j = 0; j < meshesFromObj.length; j++) {
  96299. //check meshesNames (stlFileLoader)
  96300. if (meshesNames && meshesFromObj[j].name) {
  96301. if (meshesNames instanceof Array) {
  96302. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  96303. continue;
  96304. }
  96305. }
  96306. else {
  96307. if (meshesFromObj[j].name !== meshesNames) {
  96308. continue;
  96309. }
  96310. }
  96311. }
  96312. //Get the current mesh
  96313. //Set the data with VertexBuffer for each mesh
  96314. handledMesh = meshesFromObj[j];
  96315. //Create a BABYLON.Mesh with the name of the obj mesh
  96316. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  96317. //Push the name of the material to an array
  96318. //This is indispensable for the importMesh function
  96319. materialToUse.push(meshesFromObj[j].materialName);
  96320. var vertexData = new BABYLON.VertexData(); //The container for the values
  96321. //Set the data for the babylonMesh
  96322. vertexData.positions = handledMesh.positions;
  96323. vertexData.normals = handledMesh.normals;
  96324. vertexData.uvs = handledMesh.uvs;
  96325. vertexData.indices = handledMesh.indices;
  96326. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  96327. vertexData.applyToMesh(babylonMesh);
  96328. //Push the mesh into an array
  96329. babylonMeshesArray.push(babylonMesh);
  96330. }
  96331. //load the materials
  96332. //Check if we have a file to load
  96333. if (fileToLoad !== "") {
  96334. //Load the file synchronously
  96335. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  96336. //Create materials thanks MTLLoader function
  96337. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  96338. //Look at each material loaded in the mtl file
  96339. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  96340. //Three variables to get all meshes with the same material
  96341. var startIndex = 0;
  96342. var _indices = [];
  96343. var _index;
  96344. //The material from MTL file is used in the meshes loaded
  96345. //Push the indice in an array
  96346. //Check if the material is not used for another mesh
  96347. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  96348. _indices.push(_index);
  96349. startIndex = _index + 1;
  96350. }
  96351. //If the material is not used dispose it
  96352. if (_index == -1 && _indices.length == 0) {
  96353. //If the material is not needed, remove it
  96354. materialsFromMTLFile.materials[n].dispose();
  96355. }
  96356. else {
  96357. for (var o = 0; o < _indices.length; o++) {
  96358. //Apply the material to the BABYLON.Mesh for each mesh with the material
  96359. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  96360. }
  96361. }
  96362. }
  96363. });
  96364. }
  96365. //Return an array with all BABYLON.Mesh
  96366. return babylonMeshesArray;
  96367. };
  96368. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  96369. return OBJFileLoader;
  96370. }());
  96371. BABYLON.OBJFileLoader = OBJFileLoader;
  96372. if (BABYLON.SceneLoader) {
  96373. //Add this loader into the register plugin
  96374. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  96375. }
  96376. })(BABYLON || (BABYLON = {}));
  96377. //# sourceMappingURL=babylon.objFileLoader.js.map
  96378. "use strict";
  96379. var BABYLON;
  96380. (function (BABYLON) {
  96381. var GLTFLoaderCoordinateSystemMode;
  96382. (function (GLTFLoaderCoordinateSystemMode) {
  96383. /**
  96384. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  96385. */
  96386. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  96387. /**
  96388. * Sets the useRightHandedSystem flag on the scene.
  96389. */
  96390. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  96391. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  96392. var GLTFLoaderAnimationStartMode;
  96393. (function (GLTFLoaderAnimationStartMode) {
  96394. /**
  96395. * No animation will start.
  96396. */
  96397. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  96398. /**
  96399. * The first animation will start.
  96400. */
  96401. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  96402. /**
  96403. * All animations will start.
  96404. */
  96405. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  96406. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  96407. var GLTFLoaderState;
  96408. (function (GLTFLoaderState) {
  96409. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  96410. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  96411. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  96412. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  96413. var GLTFFileLoader = /** @class */ (function () {
  96414. function GLTFFileLoader() {
  96415. // #region Common options
  96416. /**
  96417. * Raised when the asset has been parsed.
  96418. * The data.json property stores the glTF JSON.
  96419. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  96420. */
  96421. this.onParsedObservable = new BABYLON.Observable();
  96422. // #endregion
  96423. // #region V2 options
  96424. /**
  96425. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  96426. */
  96427. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  96428. /**
  96429. * The animation start mode (NONE, FIRST, ALL).
  96430. */
  96431. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  96432. /**
  96433. * Set to true to compile materials before raising the success callback.
  96434. */
  96435. this.compileMaterials = false;
  96436. /**
  96437. * Set to true to also compile materials with clip planes.
  96438. */
  96439. this.useClipPlane = false;
  96440. /**
  96441. * Set to true to compile shadow generators before raising the success callback.
  96442. */
  96443. this.compileShadowGenerators = false;
  96444. /**
  96445. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  96446. */
  96447. this.onMeshLoadedObservable = new BABYLON.Observable();
  96448. /**
  96449. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  96450. */
  96451. this.onTextureLoadedObservable = new BABYLON.Observable();
  96452. /**
  96453. * Raised when the loader creates a material after parsing the glTF properties of the material.
  96454. */
  96455. this.onMaterialLoadedObservable = new BABYLON.Observable();
  96456. /**
  96457. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  96458. */
  96459. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  96460. /**
  96461. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  96462. * For assets with LODs, raised when all of the LODs are complete.
  96463. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  96464. */
  96465. this.onCompleteObservable = new BABYLON.Observable();
  96466. /**
  96467. * Raised when the loader is disposed.
  96468. */
  96469. this.onDisposeObservable = new BABYLON.Observable();
  96470. /**
  96471. * Raised after a loader extension is created.
  96472. * Set additional options for a loader extension in this event.
  96473. */
  96474. this.onExtensionLoadedObservable = new BABYLON.Observable();
  96475. // #endregion
  96476. this._loader = null;
  96477. this.name = "gltf";
  96478. this.extensions = {
  96479. ".gltf": { isBinary: false },
  96480. ".glb": { isBinary: true }
  96481. };
  96482. }
  96483. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  96484. set: function (callback) {
  96485. if (this._onParsedObserver) {
  96486. this.onParsedObservable.remove(this._onParsedObserver);
  96487. }
  96488. this._onParsedObserver = this.onParsedObservable.add(callback);
  96489. },
  96490. enumerable: true,
  96491. configurable: true
  96492. });
  96493. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  96494. set: function (callback) {
  96495. if (this._onMeshLoadedObserver) {
  96496. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  96497. }
  96498. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  96499. },
  96500. enumerable: true,
  96501. configurable: true
  96502. });
  96503. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  96504. set: function (callback) {
  96505. if (this._onTextureLoadedObserver) {
  96506. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  96507. }
  96508. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  96509. },
  96510. enumerable: true,
  96511. configurable: true
  96512. });
  96513. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  96514. set: function (callback) {
  96515. if (this._onMaterialLoadedObserver) {
  96516. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  96517. }
  96518. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  96519. },
  96520. enumerable: true,
  96521. configurable: true
  96522. });
  96523. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  96524. set: function (callback) {
  96525. if (this._onAnimationGroupLoadedObserver) {
  96526. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  96527. }
  96528. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  96529. },
  96530. enumerable: true,
  96531. configurable: true
  96532. });
  96533. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  96534. set: function (callback) {
  96535. if (this._onCompleteObserver) {
  96536. this.onCompleteObservable.remove(this._onCompleteObserver);
  96537. }
  96538. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  96539. },
  96540. enumerable: true,
  96541. configurable: true
  96542. });
  96543. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  96544. set: function (callback) {
  96545. if (this._onDisposeObserver) {
  96546. this.onDisposeObservable.remove(this._onDisposeObserver);
  96547. }
  96548. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96549. },
  96550. enumerable: true,
  96551. configurable: true
  96552. });
  96553. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  96554. set: function (callback) {
  96555. if (this._onExtensionLoadedObserver) {
  96556. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  96557. }
  96558. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  96559. },
  96560. enumerable: true,
  96561. configurable: true
  96562. });
  96563. /**
  96564. * Gets a promise that resolves when the asset is completely loaded.
  96565. * @returns A promise that resolves when the asset is completely loaded.
  96566. */
  96567. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  96568. var _this = this;
  96569. return new Promise(function (resolve) {
  96570. _this.onCompleteObservable.add(function () {
  96571. resolve();
  96572. }, undefined, undefined, undefined, true);
  96573. });
  96574. };
  96575. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  96576. /**
  96577. * The loader state or null if not active.
  96578. */
  96579. get: function () {
  96580. return this._loader ? this._loader.state : null;
  96581. },
  96582. enumerable: true,
  96583. configurable: true
  96584. });
  96585. /**
  96586. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  96587. */
  96588. GLTFFileLoader.prototype.dispose = function () {
  96589. if (this._loader) {
  96590. this._loader.dispose();
  96591. this._loader = null;
  96592. }
  96593. this.onMeshLoadedObservable.clear();
  96594. this.onTextureLoadedObservable.clear();
  96595. this.onMaterialLoadedObservable.clear();
  96596. this.onDisposeObservable.notifyObservers(this);
  96597. this.onDisposeObservable.clear();
  96598. };
  96599. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  96600. var _this = this;
  96601. return Promise.resolve().then(function () {
  96602. var loaderData = _this._parse(data);
  96603. _this._loader = _this._getLoader(loaderData);
  96604. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  96605. });
  96606. };
  96607. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  96608. var _this = this;
  96609. return Promise.resolve().then(function () {
  96610. var loaderData = _this._parse(data);
  96611. _this._loader = _this._getLoader(loaderData);
  96612. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  96613. });
  96614. };
  96615. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  96616. var _this = this;
  96617. return Promise.resolve().then(function () {
  96618. var loaderData = _this._parse(data);
  96619. _this._loader = _this._getLoader(loaderData);
  96620. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  96621. var container = new BABYLON.AssetContainer(scene);
  96622. Array.prototype.push.apply(container.meshes, result.meshes);
  96623. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  96624. Array.prototype.push.apply(container.skeletons, result.skeletons);
  96625. container.removeAllFromScene();
  96626. return container;
  96627. });
  96628. });
  96629. };
  96630. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  96631. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  96632. };
  96633. GLTFFileLoader.prototype.createPlugin = function () {
  96634. return new GLTFFileLoader();
  96635. };
  96636. GLTFFileLoader.prototype._parse = function (data) {
  96637. var parsedData;
  96638. if (data instanceof ArrayBuffer) {
  96639. parsedData = GLTFFileLoader._parseBinary(data);
  96640. }
  96641. else {
  96642. parsedData = {
  96643. json: JSON.parse(data),
  96644. bin: null
  96645. };
  96646. }
  96647. this.onParsedObservable.notifyObservers(parsedData);
  96648. this.onParsedObservable.clear();
  96649. return parsedData;
  96650. };
  96651. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  96652. var _this = this;
  96653. var loaderVersion = { major: 2, minor: 0 };
  96654. var asset = loaderData.json.asset || {};
  96655. var version = GLTFFileLoader._parseVersion(asset.version);
  96656. if (!version) {
  96657. throw new Error("Invalid version: " + asset.version);
  96658. }
  96659. if (asset.minVersion !== undefined) {
  96660. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  96661. if (!minVersion) {
  96662. throw new Error("Invalid minimum version: " + asset.minVersion);
  96663. }
  96664. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  96665. throw new Error("Incompatible minimum version: " + asset.minVersion);
  96666. }
  96667. }
  96668. var createLoaders = {
  96669. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  96670. 2: GLTFFileLoader.CreateGLTFLoaderV2
  96671. };
  96672. var createLoader = createLoaders[version.major];
  96673. if (!createLoader) {
  96674. throw new Error("Unsupported version: " + asset.version);
  96675. }
  96676. var loader = createLoader();
  96677. loader.coordinateSystemMode = this.coordinateSystemMode;
  96678. loader.animationStartMode = this.animationStartMode;
  96679. loader.compileMaterials = this.compileMaterials;
  96680. loader.useClipPlane = this.useClipPlane;
  96681. loader.compileShadowGenerators = this.compileShadowGenerators;
  96682. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  96683. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  96684. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  96685. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  96686. loader.onAnimationGroupLoadedObservable.add(function (animationGroup) { return _this.onAnimationGroupLoadedObservable.notifyObservers(animationGroup); });
  96687. loader.onCompleteObservable.add(function () {
  96688. _this.onMeshLoadedObservable.clear();
  96689. _this.onTextureLoadedObservable.clear();
  96690. _this.onMaterialLoadedObservable.clear();
  96691. _this.onCompleteObservable.notifyObservers(_this);
  96692. _this.onCompleteObservable.clear();
  96693. });
  96694. return loader;
  96695. };
  96696. GLTFFileLoader._parseBinary = function (data) {
  96697. var Binary = {
  96698. Magic: 0x46546C67
  96699. };
  96700. var binaryReader = new BinaryReader(data);
  96701. var magic = binaryReader.readUint32();
  96702. if (magic !== Binary.Magic) {
  96703. throw new Error("Unexpected magic: " + magic);
  96704. }
  96705. var version = binaryReader.readUint32();
  96706. switch (version) {
  96707. case 1: return GLTFFileLoader._parseV1(binaryReader);
  96708. case 2: return GLTFFileLoader._parseV2(binaryReader);
  96709. }
  96710. throw new Error("Unsupported version: " + version);
  96711. };
  96712. GLTFFileLoader._parseV1 = function (binaryReader) {
  96713. var ContentFormat = {
  96714. JSON: 0
  96715. };
  96716. var length = binaryReader.readUint32();
  96717. if (length != binaryReader.getLength()) {
  96718. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96719. }
  96720. var contentLength = binaryReader.readUint32();
  96721. var contentFormat = binaryReader.readUint32();
  96722. var content;
  96723. switch (contentFormat) {
  96724. case ContentFormat.JSON: {
  96725. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  96726. break;
  96727. }
  96728. default: {
  96729. throw new Error("Unexpected content format: " + contentFormat);
  96730. }
  96731. }
  96732. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  96733. var body = binaryReader.readUint8Array(bytesRemaining);
  96734. return {
  96735. json: content,
  96736. bin: body
  96737. };
  96738. };
  96739. GLTFFileLoader._parseV2 = function (binaryReader) {
  96740. var ChunkFormat = {
  96741. JSON: 0x4E4F534A,
  96742. BIN: 0x004E4942
  96743. };
  96744. var length = binaryReader.readUint32();
  96745. if (length !== binaryReader.getLength()) {
  96746. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96747. }
  96748. // JSON chunk
  96749. var chunkLength = binaryReader.readUint32();
  96750. var chunkFormat = binaryReader.readUint32();
  96751. if (chunkFormat !== ChunkFormat.JSON) {
  96752. throw new Error("First chunk format is not JSON");
  96753. }
  96754. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  96755. // Look for BIN chunk
  96756. var bin = null;
  96757. while (binaryReader.getPosition() < binaryReader.getLength()) {
  96758. var chunkLength_1 = binaryReader.readUint32();
  96759. var chunkFormat_1 = binaryReader.readUint32();
  96760. switch (chunkFormat_1) {
  96761. case ChunkFormat.JSON: {
  96762. throw new Error("Unexpected JSON chunk");
  96763. }
  96764. case ChunkFormat.BIN: {
  96765. bin = binaryReader.readUint8Array(chunkLength_1);
  96766. break;
  96767. }
  96768. default: {
  96769. // ignore unrecognized chunkFormat
  96770. binaryReader.skipBytes(chunkLength_1);
  96771. break;
  96772. }
  96773. }
  96774. }
  96775. return {
  96776. json: json,
  96777. bin: bin
  96778. };
  96779. };
  96780. GLTFFileLoader._parseVersion = function (version) {
  96781. if (version === "1.0" || version === "1.0.1") {
  96782. return {
  96783. major: 1,
  96784. minor: 0
  96785. };
  96786. }
  96787. var match = (version + "").match(/^(\d+)\.(\d+)/);
  96788. if (!match) {
  96789. return null;
  96790. }
  96791. return {
  96792. major: parseInt(match[1]),
  96793. minor: parseInt(match[2])
  96794. };
  96795. };
  96796. GLTFFileLoader._compareVersion = function (a, b) {
  96797. if (a.major > b.major)
  96798. return 1;
  96799. if (a.major < b.major)
  96800. return -1;
  96801. if (a.minor > b.minor)
  96802. return 1;
  96803. if (a.minor < b.minor)
  96804. return -1;
  96805. return 0;
  96806. };
  96807. GLTFFileLoader._decodeBufferToText = function (buffer) {
  96808. var result = "";
  96809. var length = buffer.byteLength;
  96810. for (var i = 0; i < length; i++) {
  96811. result += String.fromCharCode(buffer[i]);
  96812. }
  96813. return result;
  96814. };
  96815. // #endregion
  96816. // #region V1 options
  96817. GLTFFileLoader.IncrementalLoading = true;
  96818. GLTFFileLoader.HomogeneousCoordinates = false;
  96819. return GLTFFileLoader;
  96820. }());
  96821. BABYLON.GLTFFileLoader = GLTFFileLoader;
  96822. var BinaryReader = /** @class */ (function () {
  96823. function BinaryReader(arrayBuffer) {
  96824. this._arrayBuffer = arrayBuffer;
  96825. this._dataView = new DataView(arrayBuffer);
  96826. this._byteOffset = 0;
  96827. }
  96828. BinaryReader.prototype.getPosition = function () {
  96829. return this._byteOffset;
  96830. };
  96831. BinaryReader.prototype.getLength = function () {
  96832. return this._arrayBuffer.byteLength;
  96833. };
  96834. BinaryReader.prototype.readUint32 = function () {
  96835. var value = this._dataView.getUint32(this._byteOffset, true);
  96836. this._byteOffset += 4;
  96837. return value;
  96838. };
  96839. BinaryReader.prototype.readUint8Array = function (length) {
  96840. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  96841. this._byteOffset += length;
  96842. return value;
  96843. };
  96844. BinaryReader.prototype.skipBytes = function (length) {
  96845. this._byteOffset += length;
  96846. };
  96847. return BinaryReader;
  96848. }());
  96849. if (BABYLON.SceneLoader) {
  96850. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  96851. }
  96852. })(BABYLON || (BABYLON = {}));
  96853. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  96854. "use strict";
  96855. var BABYLON;
  96856. (function (BABYLON) {
  96857. var GLTF1;
  96858. (function (GLTF1) {
  96859. /**
  96860. * Enums
  96861. */
  96862. var EComponentType;
  96863. (function (EComponentType) {
  96864. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  96865. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  96866. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  96867. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  96868. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  96869. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  96870. var EShaderType;
  96871. (function (EShaderType) {
  96872. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  96873. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  96874. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  96875. var EParameterType;
  96876. (function (EParameterType) {
  96877. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  96878. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  96879. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  96880. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  96881. EParameterType[EParameterType["INT"] = 5124] = "INT";
  96882. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  96883. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  96884. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  96885. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  96886. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  96887. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  96888. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  96889. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  96890. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  96891. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  96892. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  96893. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  96894. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  96895. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  96896. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  96897. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  96898. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  96899. var ETextureWrapMode;
  96900. (function (ETextureWrapMode) {
  96901. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  96902. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  96903. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  96904. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  96905. var ETextureFilterType;
  96906. (function (ETextureFilterType) {
  96907. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  96908. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  96909. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  96910. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  96911. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  96912. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  96913. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  96914. var ETextureFormat;
  96915. (function (ETextureFormat) {
  96916. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  96917. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  96918. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  96919. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  96920. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  96921. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  96922. var ECullingType;
  96923. (function (ECullingType) {
  96924. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  96925. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  96926. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  96927. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  96928. var EBlendingFunction;
  96929. (function (EBlendingFunction) {
  96930. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  96931. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  96932. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  96933. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  96934. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  96935. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  96936. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  96937. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  96938. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  96939. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  96940. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  96941. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  96942. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  96943. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  96944. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  96945. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  96946. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  96947. })(BABYLON || (BABYLON = {}));
  96948. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  96949. "use strict";
  96950. var BABYLON;
  96951. (function (BABYLON) {
  96952. var GLTF1;
  96953. (function (GLTF1) {
  96954. /**
  96955. * Tokenizer. Used for shaders compatibility
  96956. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  96957. */
  96958. var ETokenType;
  96959. (function (ETokenType) {
  96960. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  96961. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  96962. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  96963. })(ETokenType || (ETokenType = {}));
  96964. var Tokenizer = /** @class */ (function () {
  96965. function Tokenizer(toParse) {
  96966. this._pos = 0;
  96967. this.currentToken = ETokenType.UNKNOWN;
  96968. this.currentIdentifier = "";
  96969. this.currentString = "";
  96970. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  96971. this._toParse = toParse;
  96972. this._maxPos = toParse.length;
  96973. }
  96974. Tokenizer.prototype.getNextToken = function () {
  96975. if (this.isEnd())
  96976. return ETokenType.END_OF_INPUT;
  96977. this.currentString = this.read();
  96978. this.currentToken = ETokenType.UNKNOWN;
  96979. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  96980. this.currentToken = ETokenType.IDENTIFIER;
  96981. this.currentIdentifier = this.currentString;
  96982. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  96983. this.currentIdentifier += this.currentString;
  96984. this.forward();
  96985. }
  96986. }
  96987. return this.currentToken;
  96988. };
  96989. Tokenizer.prototype.peek = function () {
  96990. return this._toParse[this._pos];
  96991. };
  96992. Tokenizer.prototype.read = function () {
  96993. return this._toParse[this._pos++];
  96994. };
  96995. Tokenizer.prototype.forward = function () {
  96996. this._pos++;
  96997. };
  96998. Tokenizer.prototype.isEnd = function () {
  96999. return this._pos >= this._maxPos;
  97000. };
  97001. return Tokenizer;
  97002. }());
  97003. /**
  97004. * Values
  97005. */
  97006. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  97007. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  97008. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  97009. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  97010. /**
  97011. * Parse
  97012. */
  97013. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  97014. for (var buf in parsedBuffers) {
  97015. var parsedBuffer = parsedBuffers[buf];
  97016. gltfRuntime.buffers[buf] = parsedBuffer;
  97017. gltfRuntime.buffersCount++;
  97018. }
  97019. };
  97020. var parseShaders = function (parsedShaders, gltfRuntime) {
  97021. for (var sha in parsedShaders) {
  97022. var parsedShader = parsedShaders[sha];
  97023. gltfRuntime.shaders[sha] = parsedShader;
  97024. gltfRuntime.shaderscount++;
  97025. }
  97026. };
  97027. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  97028. for (var object in parsedObjects) {
  97029. var parsedObject = parsedObjects[object];
  97030. gltfRuntime[runtimeProperty][object] = parsedObject;
  97031. }
  97032. };
  97033. /**
  97034. * Utils
  97035. */
  97036. var normalizeUVs = function (buffer) {
  97037. if (!buffer) {
  97038. return;
  97039. }
  97040. for (var i = 0; i < buffer.length / 2; i++) {
  97041. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  97042. }
  97043. };
  97044. var getAttribute = function (attributeParameter) {
  97045. if (attributeParameter.semantic === "NORMAL") {
  97046. return "normal";
  97047. }
  97048. else if (attributeParameter.semantic === "POSITION") {
  97049. return "position";
  97050. }
  97051. else if (attributeParameter.semantic === "JOINT") {
  97052. return "matricesIndices";
  97053. }
  97054. else if (attributeParameter.semantic === "WEIGHT") {
  97055. return "matricesWeights";
  97056. }
  97057. else if (attributeParameter.semantic === "COLOR") {
  97058. return "color";
  97059. }
  97060. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  97061. var channel = Number(attributeParameter.semantic.split("_")[1]);
  97062. return "uv" + (channel === 0 ? "" : channel + 1);
  97063. }
  97064. return null;
  97065. };
  97066. /**
  97067. * Loads and creates animations
  97068. */
  97069. var loadAnimations = function (gltfRuntime) {
  97070. for (var anim in gltfRuntime.animations) {
  97071. var animation = gltfRuntime.animations[anim];
  97072. if (!animation.channels || !animation.samplers) {
  97073. continue;
  97074. }
  97075. var lastAnimation = null;
  97076. for (var i = 0; i < animation.channels.length; i++) {
  97077. // Get parameters and load buffers
  97078. var channel = animation.channels[i];
  97079. var sampler = animation.samplers[channel.sampler];
  97080. if (!sampler) {
  97081. continue;
  97082. }
  97083. var inputData = null;
  97084. var outputData = null;
  97085. if (animation.parameters) {
  97086. inputData = animation.parameters[sampler.input];
  97087. outputData = animation.parameters[sampler.output];
  97088. }
  97089. else {
  97090. inputData = sampler.input;
  97091. outputData = sampler.output;
  97092. }
  97093. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  97094. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  97095. var targetID = channel.target.id;
  97096. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  97097. if (targetNode === null) {
  97098. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  97099. }
  97100. if (targetNode === null) {
  97101. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  97102. continue;
  97103. }
  97104. var isBone = targetNode instanceof BABYLON.Bone;
  97105. // Get target path (position, rotation or scaling)
  97106. var targetPath = channel.target.path;
  97107. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  97108. if (targetPathIndex !== -1) {
  97109. targetPath = babylonAnimationPaths[targetPathIndex];
  97110. }
  97111. // Determine animation type
  97112. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  97113. if (!isBone) {
  97114. if (targetPath === "rotationQuaternion") {
  97115. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  97116. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  97117. }
  97118. else {
  97119. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  97120. }
  97121. }
  97122. // Create animation and key frames
  97123. var babylonAnimation = null;
  97124. var keys = [];
  97125. var arrayOffset = 0;
  97126. var modifyKey = false;
  97127. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  97128. babylonAnimation = lastAnimation;
  97129. modifyKey = true;
  97130. }
  97131. if (!modifyKey) {
  97132. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  97133. }
  97134. // For each frame
  97135. for (var j = 0; j < bufferInput.length; j++) {
  97136. var value = null;
  97137. if (targetPath === "rotationQuaternion") {
  97138. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  97139. arrayOffset += 4;
  97140. }
  97141. else {
  97142. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  97143. arrayOffset += 3;
  97144. }
  97145. if (isBone) {
  97146. var bone = targetNode;
  97147. var translation = BABYLON.Vector3.Zero();
  97148. var rotationQuaternion = new BABYLON.Quaternion();
  97149. var scaling = BABYLON.Vector3.Zero();
  97150. // Warning on decompose
  97151. var mat = bone.getBaseMatrix();
  97152. if (modifyKey && lastAnimation) {
  97153. mat = lastAnimation.getKeys()[j].value;
  97154. }
  97155. mat.decompose(scaling, rotationQuaternion, translation);
  97156. if (targetPath === "position") {
  97157. translation = value;
  97158. }
  97159. else if (targetPath === "rotationQuaternion") {
  97160. rotationQuaternion = value;
  97161. }
  97162. else {
  97163. scaling = value;
  97164. }
  97165. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  97166. }
  97167. if (!modifyKey) {
  97168. keys.push({
  97169. frame: bufferInput[j],
  97170. value: value
  97171. });
  97172. }
  97173. else if (lastAnimation) {
  97174. lastAnimation.getKeys()[j].value = value;
  97175. }
  97176. }
  97177. // Finish
  97178. if (!modifyKey && babylonAnimation) {
  97179. babylonAnimation.setKeys(keys);
  97180. targetNode.animations.push(babylonAnimation);
  97181. }
  97182. lastAnimation = babylonAnimation;
  97183. gltfRuntime.scene.stopAnimation(targetNode);
  97184. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  97185. }
  97186. }
  97187. };
  97188. /**
  97189. * Returns the bones transformation matrix
  97190. */
  97191. var configureBoneTransformation = function (node) {
  97192. var mat = null;
  97193. if (node.translation || node.rotation || node.scale) {
  97194. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  97195. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  97196. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  97197. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  97198. }
  97199. else {
  97200. mat = BABYLON.Matrix.FromArray(node.matrix);
  97201. }
  97202. return mat;
  97203. };
  97204. /**
  97205. * Returns the parent bone
  97206. */
  97207. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  97208. // Try to find
  97209. for (var i = 0; i < newSkeleton.bones.length; i++) {
  97210. if (newSkeleton.bones[i].name === jointName) {
  97211. return newSkeleton.bones[i];
  97212. }
  97213. }
  97214. // Not found, search in gltf nodes
  97215. var nodes = gltfRuntime.nodes;
  97216. for (var nde in nodes) {
  97217. var node = nodes[nde];
  97218. if (!node.jointName) {
  97219. continue;
  97220. }
  97221. var children = node.children;
  97222. for (var i = 0; i < children.length; i++) {
  97223. var child = gltfRuntime.nodes[children[i]];
  97224. if (!child.jointName) {
  97225. continue;
  97226. }
  97227. if (child.jointName === jointName) {
  97228. var mat = configureBoneTransformation(node);
  97229. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  97230. bone.id = nde;
  97231. return bone;
  97232. }
  97233. }
  97234. }
  97235. return null;
  97236. };
  97237. /**
  97238. * Returns the appropriate root node
  97239. */
  97240. var getNodeToRoot = function (nodesToRoot, id) {
  97241. for (var i = 0; i < nodesToRoot.length; i++) {
  97242. var nodeToRoot = nodesToRoot[i];
  97243. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  97244. var child = nodeToRoot.node.children[j];
  97245. if (child === id) {
  97246. return nodeToRoot.bone;
  97247. }
  97248. }
  97249. }
  97250. return null;
  97251. };
  97252. /**
  97253. * Returns the node with the joint name
  97254. */
  97255. var getJointNode = function (gltfRuntime, jointName) {
  97256. var nodes = gltfRuntime.nodes;
  97257. var node = nodes[jointName];
  97258. if (node) {
  97259. return {
  97260. node: node,
  97261. id: jointName
  97262. };
  97263. }
  97264. for (var nde in nodes) {
  97265. node = nodes[nde];
  97266. if (node.jointName === jointName) {
  97267. return {
  97268. node: node,
  97269. id: nde
  97270. };
  97271. }
  97272. }
  97273. return null;
  97274. };
  97275. /**
  97276. * Checks if a nodes is in joints
  97277. */
  97278. var nodeIsInJoints = function (skins, id) {
  97279. for (var i = 0; i < skins.jointNames.length; i++) {
  97280. if (skins.jointNames[i] === id) {
  97281. return true;
  97282. }
  97283. }
  97284. return false;
  97285. };
  97286. /**
  97287. * Fills the nodes to root for bones and builds hierarchy
  97288. */
  97289. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  97290. // Creates nodes for root
  97291. for (var nde in gltfRuntime.nodes) {
  97292. var node = gltfRuntime.nodes[nde];
  97293. var id = nde;
  97294. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  97295. continue;
  97296. }
  97297. // Create node to root bone
  97298. var mat = configureBoneTransformation(node);
  97299. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  97300. bone.id = id;
  97301. nodesToRoot.push({ bone: bone, node: node, id: id });
  97302. }
  97303. // Parenting
  97304. for (var i = 0; i < nodesToRoot.length; i++) {
  97305. var nodeToRoot = nodesToRoot[i];
  97306. var children = nodeToRoot.node.children;
  97307. for (var j = 0; j < children.length; j++) {
  97308. var child = null;
  97309. for (var k = 0; k < nodesToRoot.length; k++) {
  97310. if (nodesToRoot[k].id === children[j]) {
  97311. child = nodesToRoot[k];
  97312. break;
  97313. }
  97314. }
  97315. if (child) {
  97316. child.bone._parent = nodeToRoot.bone;
  97317. nodeToRoot.bone.children.push(child.bone);
  97318. }
  97319. }
  97320. }
  97321. };
  97322. /**
  97323. * Imports a skeleton
  97324. */
  97325. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  97326. if (!newSkeleton) {
  97327. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  97328. }
  97329. if (!skins.babylonSkeleton) {
  97330. return newSkeleton;
  97331. }
  97332. // Find the root bones
  97333. var nodesToRoot = [];
  97334. var nodesToRootToAdd = [];
  97335. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  97336. newSkeleton.bones = [];
  97337. // Joints
  97338. for (var i = 0; i < skins.jointNames.length; i++) {
  97339. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  97340. if (!jointNode) {
  97341. continue;
  97342. }
  97343. var node = jointNode.node;
  97344. if (!node) {
  97345. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  97346. continue;
  97347. }
  97348. var id = jointNode.id;
  97349. // Optimize, if the bone already exists...
  97350. var existingBone = gltfRuntime.scene.getBoneByID(id);
  97351. if (existingBone) {
  97352. newSkeleton.bones.push(existingBone);
  97353. continue;
  97354. }
  97355. // Search for parent bone
  97356. var foundBone = false;
  97357. var parentBone = null;
  97358. for (var j = 0; j < i; j++) {
  97359. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  97360. if (!jointNode_1) {
  97361. continue;
  97362. }
  97363. var joint = jointNode_1.node;
  97364. if (!joint) {
  97365. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  97366. continue;
  97367. }
  97368. var children = joint.children;
  97369. if (!children) {
  97370. continue;
  97371. }
  97372. foundBone = false;
  97373. for (var k = 0; k < children.length; k++) {
  97374. if (children[k] === id) {
  97375. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  97376. foundBone = true;
  97377. break;
  97378. }
  97379. }
  97380. if (foundBone) {
  97381. break;
  97382. }
  97383. }
  97384. // Create bone
  97385. var mat = configureBoneTransformation(node);
  97386. if (!parentBone && nodesToRoot.length > 0) {
  97387. parentBone = getNodeToRoot(nodesToRoot, id);
  97388. if (parentBone) {
  97389. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  97390. nodesToRootToAdd.push(parentBone);
  97391. }
  97392. }
  97393. }
  97394. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  97395. bone.id = id;
  97396. }
  97397. // Polish
  97398. var bones = newSkeleton.bones;
  97399. newSkeleton.bones = [];
  97400. for (var i = 0; i < skins.jointNames.length; i++) {
  97401. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  97402. if (!jointNode) {
  97403. continue;
  97404. }
  97405. for (var j = 0; j < bones.length; j++) {
  97406. if (bones[j].id === jointNode.id) {
  97407. newSkeleton.bones.push(bones[j]);
  97408. break;
  97409. }
  97410. }
  97411. }
  97412. newSkeleton.prepare();
  97413. // Finish
  97414. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  97415. newSkeleton.bones.push(nodesToRootToAdd[i]);
  97416. }
  97417. return newSkeleton;
  97418. };
  97419. /**
  97420. * Imports a mesh and its geometries
  97421. */
  97422. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  97423. if (!newMesh) {
  97424. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  97425. newMesh.id = id;
  97426. }
  97427. if (!node.babylonNode) {
  97428. return newMesh;
  97429. }
  97430. var subMaterials = [];
  97431. var vertexData = null;
  97432. var verticesStarts = new Array();
  97433. var verticesCounts = new Array();
  97434. var indexStarts = new Array();
  97435. var indexCounts = new Array();
  97436. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  97437. var meshID = meshes[meshIndex];
  97438. var mesh = gltfRuntime.meshes[meshID];
  97439. if (!mesh) {
  97440. continue;
  97441. }
  97442. // Positions, normals and UVs
  97443. for (var i = 0; i < mesh.primitives.length; i++) {
  97444. // Temporary vertex data
  97445. var tempVertexData = new BABYLON.VertexData();
  97446. var primitive = mesh.primitives[i];
  97447. if (primitive.mode !== 4) {
  97448. // continue;
  97449. }
  97450. var attributes = primitive.attributes;
  97451. var accessor = null;
  97452. var buffer = null;
  97453. // Set positions, normal and uvs
  97454. for (var semantic in attributes) {
  97455. // Link accessor and buffer view
  97456. accessor = gltfRuntime.accessors[attributes[semantic]];
  97457. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  97458. if (semantic === "NORMAL") {
  97459. tempVertexData.normals = new Float32Array(buffer.length);
  97460. tempVertexData.normals.set(buffer);
  97461. }
  97462. else if (semantic === "POSITION") {
  97463. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  97464. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  97465. for (var j = 0; j < buffer.length; j += 4) {
  97466. tempVertexData.positions[j] = buffer[j];
  97467. tempVertexData.positions[j + 1] = buffer[j + 1];
  97468. tempVertexData.positions[j + 2] = buffer[j + 2];
  97469. }
  97470. }
  97471. else {
  97472. tempVertexData.positions = new Float32Array(buffer.length);
  97473. tempVertexData.positions.set(buffer);
  97474. }
  97475. verticesCounts.push(tempVertexData.positions.length);
  97476. }
  97477. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  97478. var channel = Number(semantic.split("_")[1]);
  97479. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  97480. var uvs = new Float32Array(buffer.length);
  97481. uvs.set(buffer);
  97482. normalizeUVs(uvs);
  97483. tempVertexData.set(uvs, uvKind);
  97484. }
  97485. else if (semantic === "JOINT") {
  97486. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  97487. tempVertexData.matricesIndices.set(buffer);
  97488. }
  97489. else if (semantic === "WEIGHT") {
  97490. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  97491. tempVertexData.matricesWeights.set(buffer);
  97492. }
  97493. else if (semantic === "COLOR") {
  97494. tempVertexData.colors = new Float32Array(buffer.length);
  97495. tempVertexData.colors.set(buffer);
  97496. }
  97497. }
  97498. // Indices
  97499. accessor = gltfRuntime.accessors[primitive.indices];
  97500. if (accessor) {
  97501. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  97502. tempVertexData.indices = new Int32Array(buffer.length);
  97503. tempVertexData.indices.set(buffer);
  97504. indexCounts.push(tempVertexData.indices.length);
  97505. }
  97506. else {
  97507. // Set indices on the fly
  97508. var indices = [];
  97509. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  97510. indices.push(j);
  97511. }
  97512. tempVertexData.indices = new Int32Array(indices);
  97513. indexCounts.push(tempVertexData.indices.length);
  97514. }
  97515. if (!vertexData) {
  97516. vertexData = tempVertexData;
  97517. }
  97518. else {
  97519. vertexData.merge(tempVertexData);
  97520. }
  97521. // Sub material
  97522. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  97523. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  97524. // Update vertices start and index start
  97525. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  97526. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  97527. }
  97528. }
  97529. var material;
  97530. if (subMaterials.length > 1) {
  97531. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  97532. material.subMaterials = subMaterials;
  97533. }
  97534. else {
  97535. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  97536. }
  97537. if (subMaterials.length === 1) {
  97538. material = subMaterials[0];
  97539. }
  97540. if (!newMesh.material) {
  97541. newMesh.material = material;
  97542. }
  97543. // Apply geometry
  97544. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  97545. newMesh.computeWorldMatrix(true);
  97546. // Apply submeshes
  97547. newMesh.subMeshes = [];
  97548. var index = 0;
  97549. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  97550. var meshID = meshes[meshIndex];
  97551. var mesh = gltfRuntime.meshes[meshID];
  97552. if (!mesh) {
  97553. continue;
  97554. }
  97555. for (var i = 0; i < mesh.primitives.length; i++) {
  97556. if (mesh.primitives[i].mode !== 4) {
  97557. //continue;
  97558. }
  97559. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  97560. index++;
  97561. }
  97562. }
  97563. // Finish
  97564. return newMesh;
  97565. };
  97566. /**
  97567. * Configure node transformation from position, rotation and scaling
  97568. */
  97569. var configureNode = function (newNode, position, rotation, scaling) {
  97570. if (newNode.position) {
  97571. newNode.position = position;
  97572. }
  97573. if (newNode.rotationQuaternion || newNode.rotation) {
  97574. newNode.rotationQuaternion = rotation;
  97575. }
  97576. if (newNode.scaling) {
  97577. newNode.scaling = scaling;
  97578. }
  97579. };
  97580. /**
  97581. * Configures node from transformation matrix
  97582. */
  97583. var configureNodeFromMatrix = function (newNode, node, parent) {
  97584. if (node.matrix) {
  97585. var position = new BABYLON.Vector3(0, 0, 0);
  97586. var rotation = new BABYLON.Quaternion();
  97587. var scaling = new BABYLON.Vector3(0, 0, 0);
  97588. var mat = BABYLON.Matrix.FromArray(node.matrix);
  97589. mat.decompose(scaling, rotation, position);
  97590. configureNode(newNode, position, rotation, scaling);
  97591. }
  97592. else if (node.translation && node.rotation && node.scale) {
  97593. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  97594. }
  97595. newNode.computeWorldMatrix(true);
  97596. };
  97597. /**
  97598. * Imports a node
  97599. */
  97600. var importNode = function (gltfRuntime, node, id, parent) {
  97601. var lastNode = null;
  97602. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  97603. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  97604. return null;
  97605. }
  97606. }
  97607. // Meshes
  97608. if (node.skin) {
  97609. if (node.meshes) {
  97610. var skin = gltfRuntime.skins[node.skin];
  97611. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  97612. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  97613. if (newMesh.skeleton === null) {
  97614. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  97615. if (!skin.babylonSkeleton) {
  97616. skin.babylonSkeleton = newMesh.skeleton;
  97617. }
  97618. }
  97619. lastNode = newMesh;
  97620. }
  97621. }
  97622. else if (node.meshes) {
  97623. /**
  97624. * Improve meshes property
  97625. */
  97626. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  97627. lastNode = newMesh;
  97628. }
  97629. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  97630. var light = gltfRuntime.lights[node.light];
  97631. if (light) {
  97632. if (light.type === "ambient") {
  97633. var ambienLight = light[light.type];
  97634. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97635. hemiLight.name = node.name || "";
  97636. if (ambienLight.color) {
  97637. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  97638. }
  97639. lastNode = hemiLight;
  97640. }
  97641. else if (light.type === "directional") {
  97642. var directionalLight = light[light.type];
  97643. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97644. dirLight.name = node.name || "";
  97645. if (directionalLight.color) {
  97646. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  97647. }
  97648. lastNode = dirLight;
  97649. }
  97650. else if (light.type === "point") {
  97651. var pointLight = light[light.type];
  97652. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97653. ptLight.name = node.name || "";
  97654. if (pointLight.color) {
  97655. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  97656. }
  97657. lastNode = ptLight;
  97658. }
  97659. else if (light.type === "spot") {
  97660. var spotLight = light[light.type];
  97661. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  97662. spLight.name = node.name || "";
  97663. if (spotLight.color) {
  97664. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  97665. }
  97666. if (spotLight.fallOfAngle) {
  97667. spLight.angle = spotLight.fallOfAngle;
  97668. }
  97669. if (spotLight.fallOffExponent) {
  97670. spLight.exponent = spotLight.fallOffExponent;
  97671. }
  97672. lastNode = spLight;
  97673. }
  97674. }
  97675. }
  97676. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  97677. var camera = gltfRuntime.cameras[node.camera];
  97678. if (camera) {
  97679. if (camera.type === "orthographic") {
  97680. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97681. orthoCamera.name = node.name || "";
  97682. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  97683. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  97684. lastNode = orthoCamera;
  97685. }
  97686. else if (camera.type === "perspective") {
  97687. var perspectiveCamera = camera[camera.type];
  97688. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97689. persCamera.name = node.name || "";
  97690. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  97691. if (!perspectiveCamera.aspectRatio) {
  97692. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  97693. }
  97694. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  97695. persCamera.maxZ = perspectiveCamera.zfar;
  97696. persCamera.minZ = perspectiveCamera.znear;
  97697. }
  97698. lastNode = persCamera;
  97699. }
  97700. }
  97701. }
  97702. // Empty node
  97703. if (!node.jointName) {
  97704. if (node.babylonNode) {
  97705. return node.babylonNode;
  97706. }
  97707. else if (lastNode === null) {
  97708. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  97709. node.babylonNode = dummy;
  97710. lastNode = dummy;
  97711. }
  97712. }
  97713. if (lastNode !== null) {
  97714. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  97715. configureNodeFromMatrix(lastNode, node, parent);
  97716. }
  97717. else {
  97718. var translation = node.translation || [0, 0, 0];
  97719. var rotation = node.rotation || [0, 0, 0, 1];
  97720. var scale = node.scale || [1, 1, 1];
  97721. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  97722. }
  97723. lastNode.updateCache(true);
  97724. node.babylonNode = lastNode;
  97725. }
  97726. return lastNode;
  97727. };
  97728. /**
  97729. * Traverses nodes and creates them
  97730. */
  97731. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  97732. if (meshIncluded === void 0) { meshIncluded = false; }
  97733. var node = gltfRuntime.nodes[id];
  97734. var newNode = null;
  97735. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  97736. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  97737. meshIncluded = true;
  97738. }
  97739. else {
  97740. meshIncluded = false;
  97741. }
  97742. }
  97743. else {
  97744. meshIncluded = true;
  97745. }
  97746. if (!node.jointName && meshIncluded) {
  97747. newNode = importNode(gltfRuntime, node, id, parent);
  97748. if (newNode !== null) {
  97749. newNode.id = id;
  97750. newNode.parent = parent;
  97751. }
  97752. }
  97753. if (node.children) {
  97754. for (var i = 0; i < node.children.length; i++) {
  97755. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  97756. }
  97757. }
  97758. };
  97759. /**
  97760. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  97761. */
  97762. var postLoad = function (gltfRuntime) {
  97763. // Nodes
  97764. var currentScene = gltfRuntime.currentScene;
  97765. if (currentScene) {
  97766. for (var i = 0; i < currentScene.nodes.length; i++) {
  97767. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97768. }
  97769. }
  97770. else {
  97771. for (var thing in gltfRuntime.scenes) {
  97772. currentScene = gltfRuntime.scenes[thing];
  97773. for (var i = 0; i < currentScene.nodes.length; i++) {
  97774. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97775. }
  97776. }
  97777. }
  97778. // Set animations
  97779. loadAnimations(gltfRuntime);
  97780. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  97781. var skeleton = gltfRuntime.scene.skeletons[i];
  97782. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  97783. }
  97784. };
  97785. /**
  97786. * onBind shaderrs callback to set uniforms and matrices
  97787. */
  97788. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  97789. var materialValues = material.values || technique.parameters;
  97790. for (var unif in unTreatedUniforms) {
  97791. var uniform = unTreatedUniforms[unif];
  97792. var type = uniform.type;
  97793. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  97794. if (uniform.semantic && !uniform.source && !uniform.node) {
  97795. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  97796. }
  97797. else if (uniform.semantic && (uniform.source || uniform.node)) {
  97798. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  97799. if (source === null) {
  97800. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  97801. }
  97802. if (source === null) {
  97803. continue;
  97804. }
  97805. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  97806. }
  97807. }
  97808. else {
  97809. var value = materialValues[technique.uniforms[unif]];
  97810. if (!value) {
  97811. continue;
  97812. }
  97813. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  97814. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  97815. if (texture === null || texture === undefined) {
  97816. continue;
  97817. }
  97818. shaderMaterial.getEffect().setTexture(unif, texture);
  97819. }
  97820. else {
  97821. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  97822. }
  97823. }
  97824. }
  97825. onSuccess(shaderMaterial);
  97826. };
  97827. /**
  97828. * Prepare uniforms to send the only one time
  97829. * Loads the appropriate textures
  97830. */
  97831. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  97832. var materialValues = material.values || technique.parameters;
  97833. var techniqueUniforms = technique.uniforms;
  97834. /**
  97835. * Prepare values here (not matrices)
  97836. */
  97837. for (var unif in unTreatedUniforms) {
  97838. var uniform = unTreatedUniforms[unif];
  97839. var type = uniform.type;
  97840. var value = materialValues[techniqueUniforms[unif]];
  97841. if (value === undefined) {
  97842. // In case the value is the same for all materials
  97843. value = uniform.value;
  97844. }
  97845. if (!value) {
  97846. continue;
  97847. }
  97848. var onLoadTexture = function (uniformName) {
  97849. return function (texture) {
  97850. if (uniform.value && uniformName) {
  97851. // Static uniform
  97852. shaderMaterial.setTexture(uniformName, texture);
  97853. delete unTreatedUniforms[uniformName];
  97854. }
  97855. };
  97856. };
  97857. // Texture (sampler2D)
  97858. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  97859. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  97860. }
  97861. else {
  97862. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  97863. // Static uniform
  97864. delete unTreatedUniforms[unif];
  97865. }
  97866. }
  97867. }
  97868. };
  97869. /**
  97870. * Shader compilation failed
  97871. */
  97872. var onShaderCompileError = function (program, shaderMaterial, onError) {
  97873. return function (effect, error) {
  97874. shaderMaterial.dispose(true);
  97875. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  97876. };
  97877. };
  97878. /**
  97879. * Shader compilation success
  97880. */
  97881. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  97882. return function (_) {
  97883. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  97884. shaderMaterial.onBind = function (mesh) {
  97885. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  97886. };
  97887. };
  97888. };
  97889. /**
  97890. * Returns the appropriate uniform if already handled by babylon
  97891. */
  97892. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  97893. for (var unif in technique.uniforms) {
  97894. var uniform = technique.uniforms[unif];
  97895. var uniformParameter = technique.parameters[uniform];
  97896. if (tokenizer.currentIdentifier === unif) {
  97897. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  97898. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  97899. if (transformIndex !== -1) {
  97900. delete unTreatedUniforms[unif];
  97901. return babylonTransforms[transformIndex];
  97902. }
  97903. }
  97904. }
  97905. }
  97906. return tokenizer.currentIdentifier;
  97907. };
  97908. /**
  97909. * All shaders loaded. Create materials one by one
  97910. */
  97911. var importMaterials = function (gltfRuntime) {
  97912. // Create materials
  97913. for (var mat in gltfRuntime.materials) {
  97914. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  97915. }
  97916. };
  97917. /**
  97918. * Implementation of the base glTF spec
  97919. */
  97920. var GLTFLoaderBase = /** @class */ (function () {
  97921. function GLTFLoaderBase() {
  97922. }
  97923. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  97924. var gltfRuntime = {
  97925. extensions: {},
  97926. accessors: {},
  97927. buffers: {},
  97928. bufferViews: {},
  97929. meshes: {},
  97930. lights: {},
  97931. cameras: {},
  97932. nodes: {},
  97933. images: {},
  97934. textures: {},
  97935. shaders: {},
  97936. programs: {},
  97937. samplers: {},
  97938. techniques: {},
  97939. materials: {},
  97940. animations: {},
  97941. skins: {},
  97942. extensionsUsed: [],
  97943. scenes: {},
  97944. buffersCount: 0,
  97945. shaderscount: 0,
  97946. scene: scene,
  97947. rootUrl: rootUrl,
  97948. loadedBufferCount: 0,
  97949. loadedBufferViews: {},
  97950. loadedShaderCount: 0,
  97951. importOnlyMeshes: false,
  97952. dummyNodes: []
  97953. };
  97954. // Parse
  97955. if (parsedData.extensions) {
  97956. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  97957. }
  97958. if (parsedData.extensionsUsed) {
  97959. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  97960. }
  97961. if (parsedData.buffers) {
  97962. parseBuffers(parsedData.buffers, gltfRuntime);
  97963. }
  97964. if (parsedData.bufferViews) {
  97965. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  97966. }
  97967. if (parsedData.accessors) {
  97968. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  97969. }
  97970. if (parsedData.meshes) {
  97971. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  97972. }
  97973. if (parsedData.lights) {
  97974. parseObject(parsedData.lights, "lights", gltfRuntime);
  97975. }
  97976. if (parsedData.cameras) {
  97977. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  97978. }
  97979. if (parsedData.nodes) {
  97980. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  97981. }
  97982. if (parsedData.images) {
  97983. parseObject(parsedData.images, "images", gltfRuntime);
  97984. }
  97985. if (parsedData.textures) {
  97986. parseObject(parsedData.textures, "textures", gltfRuntime);
  97987. }
  97988. if (parsedData.shaders) {
  97989. parseShaders(parsedData.shaders, gltfRuntime);
  97990. }
  97991. if (parsedData.programs) {
  97992. parseObject(parsedData.programs, "programs", gltfRuntime);
  97993. }
  97994. if (parsedData.samplers) {
  97995. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  97996. }
  97997. if (parsedData.techniques) {
  97998. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  97999. }
  98000. if (parsedData.materials) {
  98001. parseObject(parsedData.materials, "materials", gltfRuntime);
  98002. }
  98003. if (parsedData.animations) {
  98004. parseObject(parsedData.animations, "animations", gltfRuntime);
  98005. }
  98006. if (parsedData.skins) {
  98007. parseObject(parsedData.skins, "skins", gltfRuntime);
  98008. }
  98009. if (parsedData.scenes) {
  98010. gltfRuntime.scenes = parsedData.scenes;
  98011. }
  98012. if (parsedData.scene && parsedData.scenes) {
  98013. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  98014. }
  98015. return gltfRuntime;
  98016. };
  98017. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98018. var buffer = gltfRuntime.buffers[id];
  98019. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  98020. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  98021. }
  98022. else {
  98023. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  98024. if (request) {
  98025. onError(request.status + " " + request.statusText);
  98026. }
  98027. });
  98028. }
  98029. };
  98030. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98031. var texture = gltfRuntime.textures[id];
  98032. if (!texture || !texture.source) {
  98033. onError("");
  98034. return;
  98035. }
  98036. if (texture.babylonTexture) {
  98037. onSuccess(null);
  98038. return;
  98039. }
  98040. var source = gltfRuntime.images[texture.source];
  98041. if (BABYLON.Tools.IsBase64(source.uri)) {
  98042. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  98043. }
  98044. else {
  98045. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  98046. if (request) {
  98047. onError(request.status + " " + request.statusText);
  98048. }
  98049. });
  98050. }
  98051. };
  98052. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98053. var texture = gltfRuntime.textures[id];
  98054. if (texture.babylonTexture) {
  98055. onSuccess(texture.babylonTexture);
  98056. return;
  98057. }
  98058. var sampler = gltfRuntime.samplers[texture.sampler];
  98059. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  98060. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  98061. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  98062. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  98063. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  98064. var blob = new Blob([buffer]);
  98065. var blobURL = URL.createObjectURL(blob);
  98066. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  98067. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  98068. if (sampler.wrapS !== undefined) {
  98069. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  98070. }
  98071. if (sampler.wrapT !== undefined) {
  98072. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  98073. }
  98074. newTexture.name = id;
  98075. texture.babylonTexture = newTexture;
  98076. onSuccess(newTexture);
  98077. };
  98078. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98079. var shader = gltfRuntime.shaders[id];
  98080. if (BABYLON.Tools.IsBase64(shader.uri)) {
  98081. var shaderString = atob(shader.uri.split(",")[1]);
  98082. if (onSuccess) {
  98083. onSuccess(shaderString);
  98084. }
  98085. }
  98086. else {
  98087. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  98088. if (request && onError) {
  98089. onError(request.status + " " + request.statusText);
  98090. }
  98091. });
  98092. }
  98093. };
  98094. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98095. var material = gltfRuntime.materials[id];
  98096. if (!material.technique) {
  98097. if (onError) {
  98098. onError("No technique found.");
  98099. }
  98100. return;
  98101. }
  98102. var technique = gltfRuntime.techniques[material.technique];
  98103. if (!technique) {
  98104. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  98105. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  98106. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  98107. onSuccess(defaultMaterial);
  98108. return;
  98109. }
  98110. var program = gltfRuntime.programs[technique.program];
  98111. var states = technique.states;
  98112. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  98113. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  98114. var newVertexShader = "";
  98115. var newPixelShader = "";
  98116. var vertexTokenizer = new Tokenizer(vertexShader);
  98117. var pixelTokenizer = new Tokenizer(pixelShader);
  98118. var unTreatedUniforms = {};
  98119. var uniforms = [];
  98120. var attributes = [];
  98121. var samplers = [];
  98122. // Fill uniform, sampler2D and attributes
  98123. for (var unif in technique.uniforms) {
  98124. var uniform = technique.uniforms[unif];
  98125. var uniformParameter = technique.parameters[uniform];
  98126. unTreatedUniforms[unif] = uniformParameter;
  98127. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  98128. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  98129. if (transformIndex !== -1) {
  98130. uniforms.push(babylonTransforms[transformIndex]);
  98131. delete unTreatedUniforms[unif];
  98132. }
  98133. else {
  98134. uniforms.push(unif);
  98135. }
  98136. }
  98137. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  98138. samplers.push(unif);
  98139. }
  98140. else {
  98141. uniforms.push(unif);
  98142. }
  98143. }
  98144. for (var attr in technique.attributes) {
  98145. var attribute = technique.attributes[attr];
  98146. var attributeParameter = technique.parameters[attribute];
  98147. if (attributeParameter.semantic) {
  98148. attributes.push(getAttribute(attributeParameter));
  98149. }
  98150. }
  98151. // Configure vertex shader
  98152. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  98153. var tokenType = vertexTokenizer.currentToken;
  98154. if (tokenType !== ETokenType.IDENTIFIER) {
  98155. newVertexShader += vertexTokenizer.currentString;
  98156. continue;
  98157. }
  98158. var foundAttribute = false;
  98159. for (var attr in technique.attributes) {
  98160. var attribute = technique.attributes[attr];
  98161. var attributeParameter = technique.parameters[attribute];
  98162. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  98163. newVertexShader += getAttribute(attributeParameter);
  98164. foundAttribute = true;
  98165. break;
  98166. }
  98167. }
  98168. if (foundAttribute) {
  98169. continue;
  98170. }
  98171. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  98172. }
  98173. // Configure pixel shader
  98174. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  98175. var tokenType = pixelTokenizer.currentToken;
  98176. if (tokenType !== ETokenType.IDENTIFIER) {
  98177. newPixelShader += pixelTokenizer.currentString;
  98178. continue;
  98179. }
  98180. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  98181. }
  98182. // Create shader material
  98183. var shaderPath = {
  98184. vertex: program.vertexShader + id,
  98185. fragment: program.fragmentShader + id
  98186. };
  98187. var options = {
  98188. attributes: attributes,
  98189. uniforms: uniforms,
  98190. samplers: samplers,
  98191. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  98192. };
  98193. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  98194. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  98195. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  98196. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  98197. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  98198. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  98199. if (states && states.functions) {
  98200. var functions = states.functions;
  98201. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  98202. shaderMaterial.backFaceCulling = false;
  98203. }
  98204. var blendFunc = functions.blendFuncSeparate;
  98205. if (blendFunc) {
  98206. 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) {
  98207. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  98208. }
  98209. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  98210. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  98211. }
  98212. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  98213. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  98214. }
  98215. 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) {
  98216. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  98217. }
  98218. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  98219. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  98220. }
  98221. 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) {
  98222. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  98223. }
  98224. }
  98225. }
  98226. };
  98227. return GLTFLoaderBase;
  98228. }());
  98229. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  98230. /**
  98231. * glTF V1 Loader
  98232. */
  98233. var GLTFLoader = /** @class */ (function () {
  98234. function GLTFLoader() {
  98235. // #region Stubs for IGLTFLoader interface
  98236. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  98237. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  98238. this.compileMaterials = false;
  98239. this.useClipPlane = false;
  98240. this.compileShadowGenerators = false;
  98241. this.onDisposeObservable = new BABYLON.Observable();
  98242. this.onMeshLoadedObservable = new BABYLON.Observable();
  98243. this.onTextureLoadedObservable = new BABYLON.Observable();
  98244. this.onMaterialLoadedObservable = new BABYLON.Observable();
  98245. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  98246. this.onCompleteObservable = new BABYLON.Observable();
  98247. this.onExtensionLoadedObservable = new BABYLON.Observable();
  98248. this.state = null;
  98249. }
  98250. GLTFLoader.RegisterExtension = function (extension) {
  98251. if (GLTFLoader.Extensions[extension.name]) {
  98252. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  98253. return;
  98254. }
  98255. GLTFLoader.Extensions[extension.name] = extension;
  98256. };
  98257. GLTFLoader.prototype.dispose = function () { };
  98258. // #endregion
  98259. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  98260. var _this = this;
  98261. scene.useRightHandedSystem = true;
  98262. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  98263. gltfRuntime.importOnlyMeshes = true;
  98264. if (meshesNames === "") {
  98265. gltfRuntime.importMeshesNames = [];
  98266. }
  98267. else if (typeof meshesNames === "string") {
  98268. gltfRuntime.importMeshesNames = [meshesNames];
  98269. }
  98270. else if (meshesNames && !(meshesNames instanceof Array)) {
  98271. gltfRuntime.importMeshesNames = [meshesNames];
  98272. }
  98273. else {
  98274. gltfRuntime.importMeshesNames = [];
  98275. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  98276. }
  98277. // Create nodes
  98278. _this._createNodes(gltfRuntime);
  98279. var meshes = new Array();
  98280. var skeletons = new Array();
  98281. // Fill arrays of meshes and skeletons
  98282. for (var nde in gltfRuntime.nodes) {
  98283. var node = gltfRuntime.nodes[nde];
  98284. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  98285. meshes.push(node.babylonNode);
  98286. }
  98287. }
  98288. for (var skl in gltfRuntime.skins) {
  98289. var skin = gltfRuntime.skins[skl];
  98290. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  98291. skeletons.push(skin.babylonSkeleton);
  98292. }
  98293. }
  98294. // Load buffers, shaders, materials, etc.
  98295. _this._loadBuffersAsync(gltfRuntime, function () {
  98296. _this._loadShadersAsync(gltfRuntime, function () {
  98297. importMaterials(gltfRuntime);
  98298. postLoad(gltfRuntime);
  98299. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  98300. onSuccess(meshes, [], skeletons);
  98301. }
  98302. });
  98303. }, onProgress);
  98304. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  98305. onSuccess(meshes, [], skeletons);
  98306. }
  98307. }, onError);
  98308. return true;
  98309. };
  98310. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  98311. var _this = this;
  98312. return new Promise(function (resolve, reject) {
  98313. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  98314. resolve({
  98315. meshes: meshes,
  98316. particleSystems: particleSystems,
  98317. skeletons: skeletons
  98318. });
  98319. }, onProgress, function (message) {
  98320. reject(new Error(message));
  98321. });
  98322. });
  98323. };
  98324. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  98325. var _this = this;
  98326. scene.useRightHandedSystem = true;
  98327. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  98328. // Load runtime extensios
  98329. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  98330. // Create nodes
  98331. _this._createNodes(gltfRuntime);
  98332. // Load buffers, shaders, materials, etc.
  98333. _this._loadBuffersAsync(gltfRuntime, function () {
  98334. _this._loadShadersAsync(gltfRuntime, function () {
  98335. importMaterials(gltfRuntime);
  98336. postLoad(gltfRuntime);
  98337. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  98338. onSuccess();
  98339. }
  98340. });
  98341. });
  98342. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  98343. onSuccess();
  98344. }
  98345. }, onError);
  98346. }, onError);
  98347. };
  98348. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  98349. var _this = this;
  98350. return new Promise(function (resolve, reject) {
  98351. _this._loadAsync(scene, data, rootUrl, function () {
  98352. resolve();
  98353. }, onProgress, function (message) {
  98354. reject(new Error(message));
  98355. });
  98356. });
  98357. };
  98358. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  98359. var hasShaders = false;
  98360. var processShader = function (sha, shader) {
  98361. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  98362. if (shaderString instanceof ArrayBuffer) {
  98363. return;
  98364. }
  98365. gltfRuntime.loadedShaderCount++;
  98366. if (shaderString) {
  98367. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  98368. }
  98369. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  98370. onload();
  98371. }
  98372. }, function () {
  98373. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  98374. });
  98375. };
  98376. for (var sha in gltfRuntime.shaders) {
  98377. hasShaders = true;
  98378. var shader = gltfRuntime.shaders[sha];
  98379. if (shader) {
  98380. processShader.bind(this, sha, shader)();
  98381. }
  98382. else {
  98383. BABYLON.Tools.Error("No shader named: " + sha);
  98384. }
  98385. }
  98386. if (!hasShaders) {
  98387. onload();
  98388. }
  98389. };
  98390. ;
  98391. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  98392. var hasBuffers = false;
  98393. var processBuffer = function (buf, buffer) {
  98394. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  98395. gltfRuntime.loadedBufferCount++;
  98396. if (bufferView) {
  98397. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  98398. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  98399. }
  98400. gltfRuntime.loadedBufferViews[buf] = bufferView;
  98401. }
  98402. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  98403. onLoad();
  98404. }
  98405. }, function () {
  98406. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  98407. });
  98408. };
  98409. for (var buf in gltfRuntime.buffers) {
  98410. hasBuffers = true;
  98411. var buffer = gltfRuntime.buffers[buf];
  98412. if (buffer) {
  98413. processBuffer.bind(this, buf, buffer)();
  98414. }
  98415. else {
  98416. BABYLON.Tools.Error("No buffer named: " + buf);
  98417. }
  98418. }
  98419. if (!hasBuffers) {
  98420. onLoad();
  98421. }
  98422. };
  98423. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  98424. var currentScene = gltfRuntime.currentScene;
  98425. if (currentScene) {
  98426. // Only one scene even if multiple scenes are defined
  98427. for (var i = 0; i < currentScene.nodes.length; i++) {
  98428. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  98429. }
  98430. }
  98431. else {
  98432. // Load all scenes
  98433. for (var thing in gltfRuntime.scenes) {
  98434. currentScene = gltfRuntime.scenes[thing];
  98435. for (var i = 0; i < currentScene.nodes.length; i++) {
  98436. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  98437. }
  98438. }
  98439. }
  98440. };
  98441. GLTFLoader.Extensions = {};
  98442. return GLTFLoader;
  98443. }());
  98444. GLTF1.GLTFLoader = GLTFLoader;
  98445. ;
  98446. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  98447. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98448. })(BABYLON || (BABYLON = {}));
  98449. //# sourceMappingURL=babylon.glTFLoader.js.map
  98450. "use strict";
  98451. var BABYLON;
  98452. (function (BABYLON) {
  98453. var GLTF1;
  98454. (function (GLTF1) {
  98455. /**
  98456. * Utils functions for GLTF
  98457. */
  98458. var GLTFUtils = /** @class */ (function () {
  98459. function GLTFUtils() {
  98460. }
  98461. /**
  98462. * Sets the given "parameter" matrix
  98463. * @param scene: the {BABYLON.Scene} object
  98464. * @param source: the source node where to pick the matrix
  98465. * @param parameter: the GLTF technique parameter
  98466. * @param uniformName: the name of the shader's uniform
  98467. * @param shaderMaterial: the shader material
  98468. */
  98469. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  98470. var mat = null;
  98471. if (parameter.semantic === "MODEL") {
  98472. mat = source.getWorldMatrix();
  98473. }
  98474. else if (parameter.semantic === "PROJECTION") {
  98475. mat = scene.getProjectionMatrix();
  98476. }
  98477. else if (parameter.semantic === "VIEW") {
  98478. mat = scene.getViewMatrix();
  98479. }
  98480. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  98481. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  98482. }
  98483. else if (parameter.semantic === "MODELVIEW") {
  98484. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  98485. }
  98486. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  98487. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  98488. }
  98489. else if (parameter.semantic === "MODELINVERSE") {
  98490. mat = source.getWorldMatrix().invert();
  98491. }
  98492. else if (parameter.semantic === "VIEWINVERSE") {
  98493. mat = scene.getViewMatrix().invert();
  98494. }
  98495. else if (parameter.semantic === "PROJECTIONINVERSE") {
  98496. mat = scene.getProjectionMatrix().invert();
  98497. }
  98498. else if (parameter.semantic === "MODELVIEWINVERSE") {
  98499. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  98500. }
  98501. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  98502. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  98503. }
  98504. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  98505. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  98506. }
  98507. else {
  98508. debugger;
  98509. }
  98510. if (mat) {
  98511. switch (parameter.type) {
  98512. case GLTF1.EParameterType.FLOAT_MAT2:
  98513. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  98514. break;
  98515. case GLTF1.EParameterType.FLOAT_MAT3:
  98516. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  98517. break;
  98518. case GLTF1.EParameterType.FLOAT_MAT4:
  98519. shaderMaterial.setMatrix(uniformName, mat);
  98520. break;
  98521. default: break;
  98522. }
  98523. }
  98524. };
  98525. /**
  98526. * Sets the given "parameter" matrix
  98527. * @param shaderMaterial: the shader material
  98528. * @param uniform: the name of the shader's uniform
  98529. * @param value: the value of the uniform
  98530. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  98531. */
  98532. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  98533. switch (type) {
  98534. case GLTF1.EParameterType.FLOAT:
  98535. shaderMaterial.setFloat(uniform, value);
  98536. return true;
  98537. case GLTF1.EParameterType.FLOAT_VEC2:
  98538. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  98539. return true;
  98540. case GLTF1.EParameterType.FLOAT_VEC3:
  98541. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  98542. return true;
  98543. case GLTF1.EParameterType.FLOAT_VEC4:
  98544. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  98545. return true;
  98546. default: return false;
  98547. }
  98548. };
  98549. /**
  98550. * Returns the wrap mode of the texture
  98551. * @param mode: the mode value
  98552. */
  98553. GLTFUtils.GetWrapMode = function (mode) {
  98554. switch (mode) {
  98555. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  98556. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  98557. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  98558. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  98559. }
  98560. };
  98561. /**
  98562. * Returns the byte stride giving an accessor
  98563. * @param accessor: the GLTF accessor objet
  98564. */
  98565. GLTFUtils.GetByteStrideFromType = function (accessor) {
  98566. // Needs this function since "byteStride" isn't requiered in glTF format
  98567. var type = accessor.type;
  98568. switch (type) {
  98569. case "VEC2": return 2;
  98570. case "VEC3": return 3;
  98571. case "VEC4": return 4;
  98572. case "MAT2": return 4;
  98573. case "MAT3": return 9;
  98574. case "MAT4": return 16;
  98575. default: return 1;
  98576. }
  98577. };
  98578. /**
  98579. * Returns the texture filter mode giving a mode value
  98580. * @param mode: the filter mode value
  98581. */
  98582. GLTFUtils.GetTextureFilterMode = function (mode) {
  98583. switch (mode) {
  98584. case GLTF1.ETextureFilterType.LINEAR:
  98585. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  98586. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98587. case GLTF1.ETextureFilterType.NEAREST:
  98588. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  98589. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  98590. }
  98591. };
  98592. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  98593. var byteOffset = bufferView.byteOffset + byteOffset;
  98594. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  98595. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  98596. throw new Error("Buffer access is out of range");
  98597. }
  98598. var buffer = loadedBufferView.buffer;
  98599. byteOffset += loadedBufferView.byteOffset;
  98600. switch (componentType) {
  98601. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  98602. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  98603. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  98604. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  98605. default: return new Float32Array(buffer, byteOffset, byteLength);
  98606. }
  98607. };
  98608. /**
  98609. * Returns a buffer from its accessor
  98610. * @param gltfRuntime: the GLTF runtime
  98611. * @param accessor: the GLTF accessor
  98612. */
  98613. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  98614. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  98615. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  98616. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  98617. };
  98618. /**
  98619. * Decodes a buffer view into a string
  98620. * @param view: the buffer view
  98621. */
  98622. GLTFUtils.DecodeBufferToText = function (view) {
  98623. var result = "";
  98624. var length = view.byteLength;
  98625. for (var i = 0; i < length; ++i) {
  98626. result += String.fromCharCode(view[i]);
  98627. }
  98628. return result;
  98629. };
  98630. /**
  98631. * Returns the default material of gltf. Related to
  98632. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  98633. * @param scene: the Babylon.js scene
  98634. */
  98635. GLTFUtils.GetDefaultMaterial = function (scene) {
  98636. if (!GLTFUtils._DefaultMaterial) {
  98637. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  98638. "precision highp float;",
  98639. "",
  98640. "uniform mat4 worldView;",
  98641. "uniform mat4 projection;",
  98642. "",
  98643. "attribute vec3 position;",
  98644. "",
  98645. "void main(void)",
  98646. "{",
  98647. " gl_Position = projection * worldView * vec4(position, 1.0);",
  98648. "}"
  98649. ].join("\n");
  98650. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  98651. "precision highp float;",
  98652. "",
  98653. "uniform vec4 u_emission;",
  98654. "",
  98655. "void main(void)",
  98656. "{",
  98657. " gl_FragColor = u_emission;",
  98658. "}"
  98659. ].join("\n");
  98660. var shaderPath = {
  98661. vertex: "GLTFDefaultMaterial",
  98662. fragment: "GLTFDefaultMaterial"
  98663. };
  98664. var options = {
  98665. attributes: ["position"],
  98666. uniforms: ["worldView", "projection", "u_emission"],
  98667. samplers: new Array(),
  98668. needAlphaBlending: false
  98669. };
  98670. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  98671. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  98672. }
  98673. return GLTFUtils._DefaultMaterial;
  98674. };
  98675. // The GLTF default material
  98676. GLTFUtils._DefaultMaterial = null;
  98677. return GLTFUtils;
  98678. }());
  98679. GLTF1.GLTFUtils = GLTFUtils;
  98680. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98681. })(BABYLON || (BABYLON = {}));
  98682. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  98683. "use strict";
  98684. var BABYLON;
  98685. (function (BABYLON) {
  98686. var GLTF1;
  98687. (function (GLTF1) {
  98688. var GLTFLoaderExtension = /** @class */ (function () {
  98689. function GLTFLoaderExtension(name) {
  98690. this._name = name;
  98691. }
  98692. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  98693. get: function () {
  98694. return this._name;
  98695. },
  98696. enumerable: true,
  98697. configurable: true
  98698. });
  98699. /**
  98700. * Defines an override for loading the runtime
  98701. * Return true to stop further extensions from loading the runtime
  98702. */
  98703. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98704. return false;
  98705. };
  98706. /**
  98707. * Defines an onverride for creating gltf runtime
  98708. * Return true to stop further extensions from creating the runtime
  98709. */
  98710. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98711. return false;
  98712. };
  98713. /**
  98714. * Defines an override for loading buffers
  98715. * Return true to stop further extensions from loading this buffer
  98716. */
  98717. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98718. return false;
  98719. };
  98720. /**
  98721. * Defines an override for loading texture buffers
  98722. * Return true to stop further extensions from loading this texture data
  98723. */
  98724. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98725. return false;
  98726. };
  98727. /**
  98728. * Defines an override for creating textures
  98729. * Return true to stop further extensions from loading this texture
  98730. */
  98731. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98732. return false;
  98733. };
  98734. /**
  98735. * Defines an override for loading shader strings
  98736. * Return true to stop further extensions from loading this shader data
  98737. */
  98738. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98739. return false;
  98740. };
  98741. /**
  98742. * Defines an override for loading materials
  98743. * Return true to stop further extensions from loading this material
  98744. */
  98745. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98746. return false;
  98747. };
  98748. // ---------
  98749. // Utilities
  98750. // ---------
  98751. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98752. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98753. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  98754. }, function () {
  98755. setTimeout(function () {
  98756. if (!onSuccess) {
  98757. return;
  98758. }
  98759. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  98760. });
  98761. });
  98762. };
  98763. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98764. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98765. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  98766. }, function () {
  98767. setTimeout(function () {
  98768. onSuccess();
  98769. });
  98770. });
  98771. };
  98772. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98773. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98774. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  98775. }, function () {
  98776. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  98777. });
  98778. };
  98779. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  98780. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  98781. if (buffer) {
  98782. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98783. }
  98784. }, onError);
  98785. };
  98786. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98787. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98788. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  98789. }, function () {
  98790. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  98791. });
  98792. };
  98793. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98794. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98795. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  98796. }, function () {
  98797. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  98798. });
  98799. };
  98800. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98801. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98802. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  98803. }, function () {
  98804. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  98805. });
  98806. };
  98807. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98808. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98809. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98810. }, function () {
  98811. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98812. });
  98813. };
  98814. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  98815. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  98816. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  98817. if (func(loaderExtension)) {
  98818. return;
  98819. }
  98820. }
  98821. defaultFunc();
  98822. };
  98823. return GLTFLoaderExtension;
  98824. }());
  98825. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  98826. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98827. })(BABYLON || (BABYLON = {}));
  98828. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  98829. "use strict";
  98830. var BABYLON;
  98831. (function (BABYLON) {
  98832. var GLTF1;
  98833. (function (GLTF1) {
  98834. var BinaryExtensionBufferName = "binary_glTF";
  98835. ;
  98836. ;
  98837. var GLTFBinaryExtension = /** @class */ (function (_super) {
  98838. __extends(GLTFBinaryExtension, _super);
  98839. function GLTFBinaryExtension() {
  98840. return _super.call(this, "KHR_binary_glTF") || this;
  98841. }
  98842. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98843. var extensionsUsed = data.json.extensionsUsed;
  98844. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  98845. return false;
  98846. }
  98847. this._bin = data.bin;
  98848. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  98849. return true;
  98850. };
  98851. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98852. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  98853. return false;
  98854. }
  98855. if (id !== BinaryExtensionBufferName) {
  98856. return false;
  98857. }
  98858. onSuccess(this._bin);
  98859. return true;
  98860. };
  98861. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98862. var texture = gltfRuntime.textures[id];
  98863. var source = gltfRuntime.images[texture.source];
  98864. if (!source.extensions || !(this.name in source.extensions)) {
  98865. return false;
  98866. }
  98867. var sourceExt = source.extensions[this.name];
  98868. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  98869. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  98870. onSuccess(buffer);
  98871. return true;
  98872. };
  98873. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98874. var shader = gltfRuntime.shaders[id];
  98875. if (!shader.extensions || !(this.name in shader.extensions)) {
  98876. return false;
  98877. }
  98878. var binaryExtensionShader = shader.extensions[this.name];
  98879. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  98880. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  98881. setTimeout(function () {
  98882. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  98883. onSuccess(shaderString);
  98884. });
  98885. return true;
  98886. };
  98887. return GLTFBinaryExtension;
  98888. }(GLTF1.GLTFLoaderExtension));
  98889. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  98890. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  98891. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98892. })(BABYLON || (BABYLON = {}));
  98893. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  98894. "use strict";
  98895. var BABYLON;
  98896. (function (BABYLON) {
  98897. var GLTF1;
  98898. (function (GLTF1) {
  98899. ;
  98900. ;
  98901. ;
  98902. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  98903. __extends(GLTFMaterialsCommonExtension, _super);
  98904. function GLTFMaterialsCommonExtension() {
  98905. return _super.call(this, "KHR_materials_common") || this;
  98906. }
  98907. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98908. if (!gltfRuntime.extensions)
  98909. return false;
  98910. var extension = gltfRuntime.extensions[this.name];
  98911. if (!extension)
  98912. return false;
  98913. // Create lights
  98914. var lights = extension.lights;
  98915. if (lights) {
  98916. for (var thing in lights) {
  98917. var light = lights[thing];
  98918. switch (light.type) {
  98919. case "ambient":
  98920. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  98921. var ambient = light.ambient;
  98922. if (ambient) {
  98923. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  98924. }
  98925. break;
  98926. case "point":
  98927. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  98928. var point = light.point;
  98929. if (point) {
  98930. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  98931. }
  98932. break;
  98933. case "directional":
  98934. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  98935. var directional = light.directional;
  98936. if (directional) {
  98937. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  98938. }
  98939. break;
  98940. case "spot":
  98941. var spot = light.spot;
  98942. if (spot) {
  98943. 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);
  98944. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  98945. }
  98946. break;
  98947. default:
  98948. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  98949. break;
  98950. }
  98951. }
  98952. }
  98953. return false;
  98954. };
  98955. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98956. var material = gltfRuntime.materials[id];
  98957. if (!material || !material.extensions)
  98958. return false;
  98959. var extension = material.extensions[this.name];
  98960. if (!extension)
  98961. return false;
  98962. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  98963. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  98964. if (extension.technique === "CONSTANT") {
  98965. standardMaterial.disableLighting = true;
  98966. }
  98967. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  98968. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  98969. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  98970. // Ambient
  98971. if (typeof extension.values.ambient === "string") {
  98972. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  98973. }
  98974. else {
  98975. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  98976. }
  98977. // Diffuse
  98978. if (typeof extension.values.diffuse === "string") {
  98979. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  98980. }
  98981. else {
  98982. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  98983. }
  98984. // Emission
  98985. if (typeof extension.values.emission === "string") {
  98986. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  98987. }
  98988. else {
  98989. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  98990. }
  98991. // Specular
  98992. if (typeof extension.values.specular === "string") {
  98993. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  98994. }
  98995. else {
  98996. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  98997. }
  98998. return true;
  98999. };
  99000. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  99001. // Create buffer from texture url
  99002. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  99003. // Create texture from buffer
  99004. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  99005. }, onError);
  99006. };
  99007. return GLTFMaterialsCommonExtension;
  99008. }(GLTF1.GLTFLoaderExtension));
  99009. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  99010. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  99011. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  99012. })(BABYLON || (BABYLON = {}));
  99013. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  99014. "use strict";
  99015. var BABYLON;
  99016. (function (BABYLON) {
  99017. var GLTF2;
  99018. (function (GLTF2) {
  99019. var ArrayItem = /** @class */ (function () {
  99020. function ArrayItem() {
  99021. }
  99022. ArrayItem.Assign = function (values) {
  99023. if (values) {
  99024. for (var index = 0; index < values.length; index++) {
  99025. values[index]._index = index;
  99026. }
  99027. }
  99028. };
  99029. return ArrayItem;
  99030. }());
  99031. GLTF2.ArrayItem = ArrayItem;
  99032. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  99033. })(BABYLON || (BABYLON = {}));
  99034. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  99035. "use strict";
  99036. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  99037. "use strict";
  99038. var BABYLON;
  99039. (function (BABYLON) {
  99040. var GLTF2;
  99041. (function (GLTF2) {
  99042. var GLTFLoader = /** @class */ (function () {
  99043. function GLTFLoader() {
  99044. this._completePromises = new Array();
  99045. this._disposed = false;
  99046. this._state = null;
  99047. this._extensions = {};
  99048. this._defaultSampler = {};
  99049. this._defaultBabylonMaterials = {};
  99050. this._requests = new Array();
  99051. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  99052. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  99053. this.compileMaterials = false;
  99054. this.useClipPlane = false;
  99055. this.compileShadowGenerators = false;
  99056. this.onDisposeObservable = new BABYLON.Observable();
  99057. this.onMeshLoadedObservable = new BABYLON.Observable();
  99058. this.onTextureLoadedObservable = new BABYLON.Observable();
  99059. this.onMaterialLoadedObservable = new BABYLON.Observable();
  99060. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  99061. this.onExtensionLoadedObservable = new BABYLON.Observable();
  99062. this.onCompleteObservable = new BABYLON.Observable();
  99063. }
  99064. GLTFLoader._Register = function (name, factory) {
  99065. if (GLTFLoader._Factories[name]) {
  99066. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  99067. return;
  99068. }
  99069. GLTFLoader._Factories[name] = factory;
  99070. // Keep the order of registration so that extensions registered first are called first.
  99071. GLTFLoader._Names.push(name);
  99072. };
  99073. Object.defineProperty(GLTFLoader.prototype, "state", {
  99074. get: function () {
  99075. return this._state;
  99076. },
  99077. enumerable: true,
  99078. configurable: true
  99079. });
  99080. GLTFLoader.prototype.dispose = function () {
  99081. if (this._disposed) {
  99082. return;
  99083. }
  99084. this._disposed = true;
  99085. this.onDisposeObservable.notifyObservers(this);
  99086. this.onDisposeObservable.clear();
  99087. this._clear();
  99088. };
  99089. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  99090. var _this = this;
  99091. return Promise.resolve().then(function () {
  99092. var nodes = null;
  99093. if (meshesNames) {
  99094. var nodeMap_1 = {};
  99095. if (_this._gltf.nodes) {
  99096. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  99097. var node = _a[_i];
  99098. if (node.name) {
  99099. nodeMap_1[node.name] = node;
  99100. }
  99101. }
  99102. }
  99103. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  99104. nodes = names.map(function (name) {
  99105. var node = nodeMap_1[name];
  99106. if (!node) {
  99107. throw new Error("Failed to find node '" + name + "'");
  99108. }
  99109. return node;
  99110. });
  99111. }
  99112. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  99113. return {
  99114. meshes: _this._getMeshes(),
  99115. particleSystems: [],
  99116. skeletons: _this._getSkeletons(),
  99117. };
  99118. });
  99119. });
  99120. };
  99121. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  99122. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  99123. };
  99124. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  99125. var _this = this;
  99126. return Promise.resolve().then(function () {
  99127. _this._loadExtensions();
  99128. _this._babylonScene = scene;
  99129. _this._rootUrl = rootUrl;
  99130. _this._progressCallback = onProgress;
  99131. _this._state = BABYLON.GLTFLoaderState.Loading;
  99132. _this._loadData(data);
  99133. _this._checkExtensions();
  99134. var promises = new Array();
  99135. if (nodes) {
  99136. promises.push(_this._loadNodesAsync(nodes));
  99137. }
  99138. else {
  99139. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  99140. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  99141. }
  99142. if (_this.compileMaterials) {
  99143. promises.push(_this._compileMaterialsAsync());
  99144. }
  99145. if (_this.compileShadowGenerators) {
  99146. promises.push(_this._compileShadowGeneratorsAsync());
  99147. }
  99148. var resultPromise = Promise.all(promises).then(function () {
  99149. _this._state = BABYLON.GLTFLoaderState.Ready;
  99150. _this._startAnimations();
  99151. });
  99152. resultPromise.then(function () {
  99153. _this._rootBabylonMesh.setEnabled(true);
  99154. BABYLON.Tools.SetImmediate(function () {
  99155. if (!_this._disposed) {
  99156. Promise.all(_this._completePromises).then(function () {
  99157. _this._state = BABYLON.GLTFLoaderState.Complete;
  99158. _this.onCompleteObservable.notifyObservers(_this);
  99159. _this.onCompleteObservable.clear();
  99160. _this._clear();
  99161. }).catch(function (error) {
  99162. BABYLON.Tools.Error("glTF Loader: " + error.message);
  99163. _this._clear();
  99164. });
  99165. }
  99166. });
  99167. });
  99168. return resultPromise;
  99169. }).catch(function (error) {
  99170. BABYLON.Tools.Error("glTF Loader: " + error.message);
  99171. _this._clear();
  99172. throw error;
  99173. });
  99174. };
  99175. GLTFLoader.prototype._loadExtensions = function () {
  99176. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  99177. var name_1 = _a[_i];
  99178. var extension = GLTFLoader._Factories[name_1](this);
  99179. this._extensions[name_1] = extension;
  99180. this.onExtensionLoadedObservable.notifyObservers(extension);
  99181. }
  99182. this.onExtensionLoadedObservable.clear();
  99183. };
  99184. GLTFLoader.prototype._loadData = function (data) {
  99185. this._gltf = data.json;
  99186. this._setupData();
  99187. if (data.bin) {
  99188. var buffers = this._gltf.buffers;
  99189. if (buffers && buffers[0] && !buffers[0].uri) {
  99190. var binaryBuffer = buffers[0];
  99191. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  99192. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  99193. }
  99194. binaryBuffer._data = Promise.resolve(data.bin);
  99195. }
  99196. else {
  99197. BABYLON.Tools.Warn("Unexpected BIN chunk");
  99198. }
  99199. }
  99200. };
  99201. GLTFLoader.prototype._setupData = function () {
  99202. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  99203. GLTF2.ArrayItem.Assign(this._gltf.animations);
  99204. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  99205. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  99206. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  99207. GLTF2.ArrayItem.Assign(this._gltf.images);
  99208. GLTF2.ArrayItem.Assign(this._gltf.materials);
  99209. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  99210. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  99211. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  99212. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  99213. GLTF2.ArrayItem.Assign(this._gltf.skins);
  99214. GLTF2.ArrayItem.Assign(this._gltf.textures);
  99215. if (this._gltf.nodes) {
  99216. var nodeParents = {};
  99217. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  99218. var node = _a[_i];
  99219. if (node.children) {
  99220. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  99221. var index = _c[_b];
  99222. nodeParents[index] = node._index;
  99223. }
  99224. }
  99225. }
  99226. var rootNode = this._createRootNode();
  99227. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  99228. var node = _e[_d];
  99229. var parentIndex = nodeParents[node._index];
  99230. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  99231. }
  99232. }
  99233. };
  99234. GLTFLoader.prototype._checkExtensions = function () {
  99235. if (this._gltf.extensionsRequired) {
  99236. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  99237. var name_2 = _a[_i];
  99238. var extension = this._extensions[name_2];
  99239. if (!extension || !extension.enabled) {
  99240. throw new Error("Require extension " + name_2 + " is not available");
  99241. }
  99242. }
  99243. }
  99244. };
  99245. GLTFLoader.prototype._createRootNode = function () {
  99246. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  99247. this._rootBabylonMesh.setEnabled(false);
  99248. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  99249. switch (this.coordinateSystemMode) {
  99250. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  99251. if (!this._babylonScene.useRightHandedSystem) {
  99252. rootNode.rotation = [0, 1, 0, 0];
  99253. rootNode.scale = [1, 1, -1];
  99254. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  99255. }
  99256. break;
  99257. }
  99258. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  99259. this._babylonScene.useRightHandedSystem = true;
  99260. break;
  99261. }
  99262. default: {
  99263. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  99264. }
  99265. }
  99266. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  99267. return rootNode;
  99268. };
  99269. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  99270. var promises = new Array();
  99271. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  99272. var node = nodes_1[_i];
  99273. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  99274. }
  99275. promises.push(this._loadAnimationsAsync());
  99276. return Promise.all(promises).then(function () { });
  99277. };
  99278. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  99279. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  99280. if (promise) {
  99281. return promise;
  99282. }
  99283. var promises = new Array();
  99284. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  99285. var index = _a[_i];
  99286. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  99287. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  99288. }
  99289. promises.push(this._loadAnimationsAsync());
  99290. return Promise.all(promises).then(function () { });
  99291. };
  99292. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  99293. if (node._primitiveBabylonMeshes) {
  99294. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  99295. var babylonMesh = _a[_i];
  99296. callback(babylonMesh);
  99297. }
  99298. }
  99299. else {
  99300. callback(node._babylonMesh);
  99301. }
  99302. };
  99303. GLTFLoader.prototype._getMeshes = function () {
  99304. var meshes = new Array();
  99305. // Root mesh is always first.
  99306. meshes.push(this._rootBabylonMesh);
  99307. var nodes = this._gltf.nodes;
  99308. if (nodes) {
  99309. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  99310. var node = nodes_2[_i];
  99311. if (node._babylonMesh) {
  99312. meshes.push(node._babylonMesh);
  99313. }
  99314. if (node._primitiveBabylonMeshes) {
  99315. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  99316. var babylonMesh = _b[_a];
  99317. meshes.push(babylonMesh);
  99318. }
  99319. }
  99320. }
  99321. }
  99322. return meshes;
  99323. };
  99324. GLTFLoader.prototype._getSkeletons = function () {
  99325. var skeletons = new Array();
  99326. var skins = this._gltf.skins;
  99327. if (skins) {
  99328. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  99329. var skin = skins_1[_i];
  99330. if (skin._babylonSkeleton) {
  99331. skeletons.push(skin._babylonSkeleton);
  99332. }
  99333. }
  99334. }
  99335. return skeletons;
  99336. };
  99337. GLTFLoader.prototype._startAnimations = function () {
  99338. var animations = this._gltf.animations;
  99339. if (!animations) {
  99340. return;
  99341. }
  99342. switch (this.animationStartMode) {
  99343. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  99344. // do nothing
  99345. break;
  99346. }
  99347. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  99348. var animation = animations[0];
  99349. animation._babylonAnimationGroup.start(true);
  99350. break;
  99351. }
  99352. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  99353. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  99354. var animation = animations_1[_i];
  99355. animation._babylonAnimationGroup.start(true);
  99356. }
  99357. break;
  99358. }
  99359. default: {
  99360. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  99361. return;
  99362. }
  99363. }
  99364. };
  99365. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  99366. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  99367. if (promise) {
  99368. return promise;
  99369. }
  99370. if (node._babylonMesh) {
  99371. throw new Error(context + ": Invalid recursive node hierarchy");
  99372. }
  99373. var promises = new Array();
  99374. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  99375. node._babylonMesh = babylonMesh;
  99376. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  99377. node._babylonAnimationTargets.push(babylonMesh);
  99378. GLTFLoader._LoadTransform(node, babylonMesh);
  99379. if (node.mesh != undefined) {
  99380. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  99381. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  99382. }
  99383. if (node.children) {
  99384. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  99385. var index = _a[_i];
  99386. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  99387. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  99388. }
  99389. }
  99390. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  99391. return Promise.all(promises).then(function () { });
  99392. };
  99393. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  99394. // TODO: instancing
  99395. var _this = this;
  99396. var promises = new Array();
  99397. var primitives = mesh.primitives;
  99398. if (!primitives || primitives.length === 0) {
  99399. throw new Error(context + ": Primitives are missing");
  99400. }
  99401. GLTF2.ArrayItem.Assign(primitives);
  99402. if (primitives.length === 1) {
  99403. var primitive = primitives[0];
  99404. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  99405. }
  99406. else {
  99407. node._primitiveBabylonMeshes = [];
  99408. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  99409. var primitive = primitives_1[_i];
  99410. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  99411. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  99412. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  99413. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  99414. }
  99415. }
  99416. if (node.skin != undefined) {
  99417. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  99418. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  99419. }
  99420. return Promise.all(promises).then(function () {
  99421. _this._forEachPrimitive(node, function (babylonMesh) {
  99422. babylonMesh._refreshBoundingInfo(true);
  99423. });
  99424. });
  99425. };
  99426. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  99427. var _this = this;
  99428. var promises = new Array();
  99429. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  99430. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  99431. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  99432. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  99433. }));
  99434. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  99435. if (primitive.material == undefined) {
  99436. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  99437. }
  99438. else {
  99439. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  99440. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  99441. babylonMesh.material = babylonMaterial;
  99442. }));
  99443. }
  99444. return Promise.all(promises).then(function () { });
  99445. };
  99446. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  99447. var _this = this;
  99448. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  99449. if (promise) {
  99450. return promise;
  99451. }
  99452. var attributes = primitive.attributes;
  99453. if (!attributes) {
  99454. throw new Error(context + ": Attributes are missing");
  99455. }
  99456. var promises = new Array();
  99457. var babylonVertexData = new BABYLON.VertexData();
  99458. if (primitive.indices == undefined) {
  99459. var positionAccessorIndex = attributes["POSITION"];
  99460. if (positionAccessorIndex != undefined) {
  99461. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  99462. babylonVertexData.indices = new Uint32Array(accessor.count);
  99463. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  99464. babylonVertexData.indices[i] = i;
  99465. }
  99466. }
  99467. }
  99468. else {
  99469. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  99470. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  99471. babylonVertexData.indices = data;
  99472. }));
  99473. }
  99474. var loadAttribute = function (attribute, kind) {
  99475. if (attributes[attribute] == undefined) {
  99476. return;
  99477. }
  99478. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  99479. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  99480. babylonMesh._delayInfo.push(kind);
  99481. }
  99482. if (attribute === "COLOR_0") {
  99483. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  99484. babylonMesh.hasVertexAlpha = true;
  99485. }
  99486. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  99487. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99488. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  99489. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  99490. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  99491. }
  99492. babylonVertexData.set(attributeData, kind);
  99493. }));
  99494. };
  99495. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  99496. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  99497. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  99498. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  99499. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  99500. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  99501. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  99502. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  99503. return Promise.all(promises).then(function () {
  99504. return babylonVertexData;
  99505. });
  99506. };
  99507. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  99508. if (!primitive.targets) {
  99509. return;
  99510. }
  99511. if (node._numMorphTargets == undefined) {
  99512. node._numMorphTargets = primitive.targets.length;
  99513. }
  99514. else if (primitive.targets.length !== node._numMorphTargets) {
  99515. throw new Error(context + ": Primitives do not have the same number of targets");
  99516. }
  99517. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  99518. for (var index = 0; index < primitive.targets.length; index++) {
  99519. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  99520. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  99521. // TODO: tell the target whether it has positions, normals, tangents
  99522. }
  99523. };
  99524. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  99525. if (!primitive.targets) {
  99526. return Promise.resolve();
  99527. }
  99528. var promises = new Array();
  99529. var morphTargetManager = babylonMesh.morphTargetManager;
  99530. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  99531. var babylonMorphTarget = morphTargetManager.getTarget(index);
  99532. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  99533. }
  99534. return Promise.all(promises).then(function () { });
  99535. };
  99536. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  99537. var _this = this;
  99538. var promises = new Array();
  99539. var loadAttribute = function (attribute, setData) {
  99540. if (attributes[attribute] == undefined) {
  99541. return;
  99542. }
  99543. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  99544. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99545. setData(data);
  99546. }));
  99547. };
  99548. loadAttribute("POSITION", function (data) {
  99549. if (babylonVertexData.positions) {
  99550. for (var i = 0; i < data.length; i++) {
  99551. data[i] += babylonVertexData.positions[i];
  99552. }
  99553. babylonMorphTarget.setPositions(data);
  99554. }
  99555. });
  99556. loadAttribute("NORMAL", function (data) {
  99557. if (babylonVertexData.normals) {
  99558. for (var i = 0; i < data.length; i++) {
  99559. data[i] += babylonVertexData.normals[i];
  99560. }
  99561. babylonMorphTarget.setNormals(data);
  99562. }
  99563. });
  99564. loadAttribute("TANGENT", function (data) {
  99565. if (babylonVertexData.tangents) {
  99566. // Tangent data for morph targets is stored as xyz delta.
  99567. // The vertexData.tangent is stored as xyzw.
  99568. // So we need to skip every fourth vertexData.tangent.
  99569. for (var i = 0, j = 0; i < data.length; i++) {
  99570. data[i] += babylonVertexData.tangents[j++];
  99571. if ((i + 1) % 3 == 0) {
  99572. j++;
  99573. }
  99574. }
  99575. babylonMorphTarget.setTangents(data);
  99576. }
  99577. });
  99578. return Promise.all(promises).then(function () { });
  99579. };
  99580. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  99581. if (accessor.componentType == 5126 /* FLOAT */) {
  99582. return data;
  99583. }
  99584. var factor = 1;
  99585. if (accessor.normalized) {
  99586. switch (accessor.componentType) {
  99587. case 5121 /* UNSIGNED_BYTE */: {
  99588. factor = 1 / 255;
  99589. break;
  99590. }
  99591. case 5123 /* UNSIGNED_SHORT */: {
  99592. factor = 1 / 65535;
  99593. break;
  99594. }
  99595. default: {
  99596. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  99597. }
  99598. }
  99599. }
  99600. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  99601. for (var i = 0; i < result.length; i++) {
  99602. result[i] = data[i] * factor;
  99603. }
  99604. return result;
  99605. };
  99606. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  99607. var result = new Float32Array(data.length / 3 * 4);
  99608. var offset = 0;
  99609. for (var i = 0; i < result.length; i++) {
  99610. if ((i + 1) % 4 === 0) {
  99611. result[i] = 1;
  99612. }
  99613. else {
  99614. result[i] = data[offset++];
  99615. }
  99616. }
  99617. return result;
  99618. };
  99619. GLTFLoader._LoadTransform = function (node, babylonNode) {
  99620. var position = BABYLON.Vector3.Zero();
  99621. var rotation = BABYLON.Quaternion.Identity();
  99622. var scaling = BABYLON.Vector3.One();
  99623. if (node.matrix) {
  99624. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  99625. matrix.decompose(scaling, rotation, position);
  99626. }
  99627. else {
  99628. if (node.translation)
  99629. position = BABYLON.Vector3.FromArray(node.translation);
  99630. if (node.rotation)
  99631. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  99632. if (node.scale)
  99633. scaling = BABYLON.Vector3.FromArray(node.scale);
  99634. }
  99635. babylonNode.position = position;
  99636. babylonNode.rotationQuaternion = rotation;
  99637. babylonNode.scaling = scaling;
  99638. };
  99639. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  99640. var _this = this;
  99641. var assignSkeleton = function () {
  99642. _this._forEachPrimitive(node, function (babylonMesh) {
  99643. babylonMesh.skeleton = skin._babylonSkeleton;
  99644. });
  99645. node._babylonMesh.parent = _this._rootBabylonMesh;
  99646. node._babylonMesh.position = BABYLON.Vector3.Zero();
  99647. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  99648. node._babylonMesh.scaling = BABYLON.Vector3.One();
  99649. };
  99650. if (skin._loaded) {
  99651. return skin._loaded.then(function () {
  99652. assignSkeleton();
  99653. });
  99654. }
  99655. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  99656. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  99657. var skeletonId = "skeleton" + skin._index;
  99658. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  99659. skin._babylonSkeleton = babylonSkeleton;
  99660. _this._loadBones(context, skin, inverseBindMatricesData);
  99661. assignSkeleton();
  99662. }));
  99663. };
  99664. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  99665. if (skin.inverseBindMatrices == undefined) {
  99666. return Promise.resolve(null);
  99667. }
  99668. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  99669. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99670. return data;
  99671. });
  99672. };
  99673. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  99674. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  99675. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  99676. node._babylonAnimationTargets.push(babylonBone);
  99677. return babylonBone;
  99678. };
  99679. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  99680. var babylonBones = {};
  99681. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  99682. var index = _a[_i];
  99683. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  99684. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  99685. }
  99686. };
  99687. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  99688. var babylonBone = babylonBones[node._index];
  99689. if (babylonBone) {
  99690. return babylonBone;
  99691. }
  99692. var boneIndex = skin.joints.indexOf(node._index);
  99693. var baseMatrix = BABYLON.Matrix.Identity();
  99694. if (inverseBindMatricesData && boneIndex !== -1) {
  99695. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  99696. baseMatrix.invertToRef(baseMatrix);
  99697. }
  99698. var babylonParentBone = null;
  99699. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  99700. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  99701. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  99702. }
  99703. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  99704. babylonBones[node._index] = babylonBone;
  99705. return babylonBone;
  99706. };
  99707. GLTFLoader.prototype._getNodeMatrix = function (node) {
  99708. return node.matrix ?
  99709. BABYLON.Matrix.FromArray(node.matrix) :
  99710. 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());
  99711. };
  99712. GLTFLoader.prototype._loadAnimationsAsync = function () {
  99713. var animations = this._gltf.animations;
  99714. if (!animations) {
  99715. return Promise.resolve();
  99716. }
  99717. var promises = new Array();
  99718. for (var index = 0; index < animations.length; index++) {
  99719. var animation = animations[index];
  99720. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  99721. }
  99722. return Promise.all(promises).then(function () { });
  99723. };
  99724. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  99725. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  99726. animation._babylonAnimationGroup = babylonAnimationGroup;
  99727. var promises = new Array();
  99728. GLTF2.ArrayItem.Assign(animation.channels);
  99729. GLTF2.ArrayItem.Assign(animation.samplers);
  99730. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  99731. var channel = _a[_i];
  99732. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  99733. }
  99734. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  99735. return Promise.all(promises).then(function () {
  99736. babylonAnimationGroup.normalize();
  99737. });
  99738. };
  99739. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  99740. var _this = this;
  99741. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  99742. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  99743. return Promise.resolve();
  99744. }
  99745. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  99746. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  99747. var targetPath;
  99748. var animationType;
  99749. switch (channel.target.path) {
  99750. case "translation" /* TRANSLATION */: {
  99751. targetPath = "position";
  99752. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99753. break;
  99754. }
  99755. case "rotation" /* ROTATION */: {
  99756. targetPath = "rotationQuaternion";
  99757. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  99758. break;
  99759. }
  99760. case "scale" /* SCALE */: {
  99761. targetPath = "scaling";
  99762. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99763. break;
  99764. }
  99765. case "weights" /* WEIGHTS */: {
  99766. targetPath = "influence";
  99767. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  99768. break;
  99769. }
  99770. default: {
  99771. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  99772. }
  99773. }
  99774. var outputBufferOffset = 0;
  99775. var getNextOutputValue;
  99776. switch (targetPath) {
  99777. case "position": {
  99778. getNextOutputValue = function () {
  99779. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  99780. outputBufferOffset += 3;
  99781. return value;
  99782. };
  99783. break;
  99784. }
  99785. case "rotationQuaternion": {
  99786. getNextOutputValue = function () {
  99787. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  99788. outputBufferOffset += 4;
  99789. return value;
  99790. };
  99791. break;
  99792. }
  99793. case "scaling": {
  99794. getNextOutputValue = function () {
  99795. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  99796. outputBufferOffset += 3;
  99797. return value;
  99798. };
  99799. break;
  99800. }
  99801. case "influence": {
  99802. getNextOutputValue = function () {
  99803. var value = new Array(targetNode._numMorphTargets);
  99804. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  99805. value[i] = data.output[outputBufferOffset++];
  99806. }
  99807. return value;
  99808. };
  99809. break;
  99810. }
  99811. }
  99812. var getNextKey;
  99813. switch (data.interpolation) {
  99814. case "STEP" /* STEP */: {
  99815. getNextKey = function (frameIndex) { return ({
  99816. frame: data.input[frameIndex],
  99817. value: getNextOutputValue(),
  99818. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  99819. }); };
  99820. break;
  99821. }
  99822. case "LINEAR" /* LINEAR */: {
  99823. getNextKey = function (frameIndex) { return ({
  99824. frame: data.input[frameIndex],
  99825. value: getNextOutputValue()
  99826. }); };
  99827. break;
  99828. }
  99829. case "CUBICSPLINE" /* CUBICSPLINE */: {
  99830. getNextKey = function (frameIndex) { return ({
  99831. frame: data.input[frameIndex],
  99832. inTangent: getNextOutputValue(),
  99833. value: getNextOutputValue(),
  99834. outTangent: getNextOutputValue()
  99835. }); };
  99836. break;
  99837. }
  99838. }
  99839. var keys = new Array(data.input.length);
  99840. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  99841. keys[frameIndex] = getNextKey(frameIndex);
  99842. }
  99843. if (targetPath === "influence") {
  99844. var _loop_1 = function (targetIndex) {
  99845. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  99846. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  99847. babylonAnimation.setKeys(keys.map(function (key) { return ({
  99848. frame: key.frame,
  99849. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  99850. value: key.value[targetIndex],
  99851. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  99852. }); }));
  99853. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  99854. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  99855. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  99856. });
  99857. };
  99858. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  99859. _loop_1(targetIndex);
  99860. }
  99861. }
  99862. else {
  99863. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  99864. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  99865. babylonAnimation.setKeys(keys);
  99866. if (targetNode._babylonAnimationTargets) {
  99867. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  99868. var target = _a[_i];
  99869. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  99870. }
  99871. }
  99872. }
  99873. });
  99874. };
  99875. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  99876. if (sampler._data) {
  99877. return sampler._data;
  99878. }
  99879. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  99880. switch (interpolation) {
  99881. case "STEP" /* STEP */:
  99882. case "LINEAR" /* LINEAR */:
  99883. case "CUBICSPLINE" /* CUBICSPLINE */: {
  99884. break;
  99885. }
  99886. default: {
  99887. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  99888. }
  99889. }
  99890. var inputData;
  99891. var outputData;
  99892. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  99893. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  99894. sampler._data = Promise.all([
  99895. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  99896. inputData = data;
  99897. }),
  99898. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  99899. outputData = data;
  99900. })
  99901. ]).then(function () {
  99902. return {
  99903. input: inputData,
  99904. interpolation: interpolation,
  99905. output: outputData,
  99906. };
  99907. });
  99908. return sampler._data;
  99909. };
  99910. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  99911. if (buffer._data) {
  99912. return buffer._data;
  99913. }
  99914. if (!buffer.uri) {
  99915. throw new Error(context + ": Uri is missing");
  99916. }
  99917. buffer._data = this._loadUriAsync(context, buffer.uri);
  99918. return buffer._data;
  99919. };
  99920. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  99921. if (bufferView._data) {
  99922. return bufferView._data;
  99923. }
  99924. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  99925. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  99926. try {
  99927. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  99928. }
  99929. catch (e) {
  99930. throw new Error(context + ": " + e.message);
  99931. }
  99932. });
  99933. return bufferView._data;
  99934. };
  99935. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  99936. var _this = this;
  99937. if (accessor.sparse) {
  99938. throw new Error(context + ": Sparse accessors are not currently supported");
  99939. }
  99940. if (accessor._data) {
  99941. return accessor._data;
  99942. }
  99943. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  99944. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  99945. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  99946. var byteOffset = accessor.byteOffset || 0;
  99947. var byteStride = bufferView.byteStride;
  99948. if (byteStride === 0) {
  99949. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  99950. }
  99951. try {
  99952. switch (accessor.componentType) {
  99953. case 5120 /* BYTE */: {
  99954. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99955. }
  99956. case 5121 /* UNSIGNED_BYTE */: {
  99957. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99958. }
  99959. case 5122 /* SHORT */: {
  99960. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99961. }
  99962. case 5123 /* UNSIGNED_SHORT */: {
  99963. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99964. }
  99965. case 5125 /* UNSIGNED_INT */: {
  99966. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99967. }
  99968. case 5126 /* FLOAT */: {
  99969. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99970. }
  99971. default: {
  99972. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  99973. }
  99974. }
  99975. }
  99976. catch (e) {
  99977. throw new Error(context + ": " + e.messsage);
  99978. }
  99979. });
  99980. return accessor._data;
  99981. };
  99982. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  99983. byteOffset += data.byteOffset;
  99984. var targetLength = count * numComponents;
  99985. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  99986. return new typedArray(data.buffer, byteOffset, targetLength);
  99987. }
  99988. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  99989. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  99990. var targetBuffer = new typedArray(targetLength);
  99991. var sourceIndex = 0;
  99992. var targetIndex = 0;
  99993. while (targetIndex < targetLength) {
  99994. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  99995. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  99996. targetIndex++;
  99997. }
  99998. sourceIndex += elementStride;
  99999. }
  100000. return targetBuffer;
  100001. };
  100002. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  100003. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  100004. if (!babylonMaterial) {
  100005. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  100006. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  100007. babylonMaterial.metallic = 1;
  100008. babylonMaterial.roughness = 1;
  100009. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  100010. }
  100011. return babylonMaterial;
  100012. };
  100013. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  100014. var promises = new Array();
  100015. // Ensure metallic workflow
  100016. babylonMaterial.metallic = 1;
  100017. babylonMaterial.roughness = 1;
  100018. var properties = material.pbrMetallicRoughness;
  100019. if (properties) {
  100020. if (properties.baseColorFactor) {
  100021. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  100022. babylonMaterial.alpha = properties.baseColorFactor[3];
  100023. }
  100024. else {
  100025. babylonMaterial.albedoColor = BABYLON.Color3.White();
  100026. }
  100027. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  100028. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  100029. if (properties.baseColorTexture) {
  100030. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  100031. babylonMaterial.albedoTexture = texture;
  100032. }));
  100033. }
  100034. if (properties.metallicRoughnessTexture) {
  100035. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  100036. babylonMaterial.metallicTexture = texture;
  100037. }));
  100038. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  100039. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  100040. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  100041. }
  100042. }
  100043. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  100044. return Promise.all(promises).then(function () { });
  100045. };
  100046. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100047. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  100048. if (promise) {
  100049. return promise;
  100050. }
  100051. material._babylonData = material._babylonData || {};
  100052. var babylonData = material._babylonData[babylonDrawMode];
  100053. if (!babylonData) {
  100054. var promises = new Array();
  100055. var name_3 = material.name || "materialSG_" + material._index;
  100056. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  100057. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  100058. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  100059. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  100060. babylonData = {
  100061. material: babylonMaterial,
  100062. meshes: [],
  100063. loaded: Promise.all(promises).then(function () { })
  100064. };
  100065. material._babylonData[babylonDrawMode] = babylonData;
  100066. }
  100067. babylonData.meshes.push(babylonMesh);
  100068. assign(babylonData.material);
  100069. return babylonData.loaded;
  100070. };
  100071. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  100072. var babylonMaterial = new type(name, this._babylonScene);
  100073. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  100074. babylonMaterial.fillMode = drawMode;
  100075. return babylonMaterial;
  100076. };
  100077. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  100078. var promises = new Array();
  100079. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  100080. if (material.doubleSided) {
  100081. babylonMaterial.backFaceCulling = false;
  100082. babylonMaterial.twoSidedLighting = true;
  100083. }
  100084. if (material.normalTexture) {
  100085. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  100086. babylonMaterial.bumpTexture = texture;
  100087. }));
  100088. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  100089. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  100090. if (material.normalTexture.scale != undefined) {
  100091. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  100092. }
  100093. }
  100094. if (material.occlusionTexture) {
  100095. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  100096. babylonMaterial.ambientTexture = texture;
  100097. }));
  100098. babylonMaterial.useAmbientInGrayScale = true;
  100099. if (material.occlusionTexture.strength != undefined) {
  100100. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  100101. }
  100102. }
  100103. if (material.emissiveTexture) {
  100104. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  100105. babylonMaterial.emissiveTexture = texture;
  100106. }));
  100107. }
  100108. return Promise.all(promises).then(function () { });
  100109. };
  100110. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  100111. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  100112. switch (alphaMode) {
  100113. case "OPAQUE" /* OPAQUE */: {
  100114. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  100115. break;
  100116. }
  100117. case "MASK" /* MASK */: {
  100118. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  100119. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  100120. if (babylonMaterial.albedoTexture) {
  100121. babylonMaterial.albedoTexture.hasAlpha = true;
  100122. }
  100123. break;
  100124. }
  100125. case "BLEND" /* BLEND */: {
  100126. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  100127. if (babylonMaterial.albedoTexture) {
  100128. babylonMaterial.albedoTexture.hasAlpha = true;
  100129. babylonMaterial.useAlphaFromAlbedoTexture = true;
  100130. }
  100131. break;
  100132. }
  100133. default: {
  100134. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  100135. }
  100136. }
  100137. };
  100138. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  100139. var _this = this;
  100140. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  100141. context = "#/textures/" + textureInfo.index;
  100142. var promises = new Array();
  100143. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  100144. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  100145. var deferred = new BABYLON.Deferred();
  100146. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  100147. if (!_this._disposed) {
  100148. deferred.resolve();
  100149. }
  100150. }, function (message, exception) {
  100151. if (!_this._disposed) {
  100152. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  100153. }
  100154. });
  100155. promises.push(deferred.promise);
  100156. babylonTexture.name = texture.name || "texture" + texture._index;
  100157. babylonTexture.wrapU = samplerData.wrapU;
  100158. babylonTexture.wrapV = samplerData.wrapV;
  100159. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  100160. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  100161. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  100162. babylonTexture.updateURL(objectURL);
  100163. }));
  100164. assign(babylonTexture);
  100165. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  100166. return Promise.all(promises).then(function () { });
  100167. };
  100168. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  100169. if (!sampler._data) {
  100170. sampler._data = {
  100171. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  100172. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  100173. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  100174. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  100175. };
  100176. }
  100177. ;
  100178. return sampler._data;
  100179. };
  100180. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  100181. if (image._objectURL) {
  100182. return image._objectURL;
  100183. }
  100184. var promise;
  100185. if (image.uri) {
  100186. promise = this._loadUriAsync(context, image.uri);
  100187. }
  100188. else {
  100189. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  100190. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  100191. }
  100192. image._objectURL = promise.then(function (data) {
  100193. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  100194. });
  100195. return image._objectURL;
  100196. };
  100197. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  100198. var _this = this;
  100199. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  100200. if (promise) {
  100201. return promise;
  100202. }
  100203. if (!GLTFLoader._ValidateUri(uri)) {
  100204. throw new Error(context + ": Uri '" + uri + "' is invalid");
  100205. }
  100206. if (BABYLON.Tools.IsBase64(uri)) {
  100207. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  100208. }
  100209. return new Promise(function (resolve, reject) {
  100210. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  100211. if (!_this._disposed) {
  100212. resolve(new Uint8Array(data));
  100213. }
  100214. }, function (event) {
  100215. if (!_this._disposed) {
  100216. try {
  100217. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  100218. request._lengthComputable = event.lengthComputable;
  100219. request._loaded = event.loaded;
  100220. request._total = event.total;
  100221. _this._onProgress();
  100222. }
  100223. }
  100224. catch (e) {
  100225. reject(e);
  100226. }
  100227. }
  100228. }, _this._babylonScene.database, true, function (request, exception) {
  100229. if (!_this._disposed) {
  100230. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  100231. }
  100232. });
  100233. _this._requests.push(request);
  100234. });
  100235. };
  100236. GLTFLoader.prototype._onProgress = function () {
  100237. if (!this._progressCallback) {
  100238. return;
  100239. }
  100240. var lengthComputable = true;
  100241. var loaded = 0;
  100242. var total = 0;
  100243. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  100244. var request = _a[_i];
  100245. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  100246. return;
  100247. }
  100248. lengthComputable = lengthComputable && request._lengthComputable;
  100249. loaded += request._loaded;
  100250. total += request._total;
  100251. }
  100252. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  100253. };
  100254. GLTFLoader._GetProperty = function (context, array, index) {
  100255. if (!array || index == undefined || !array[index]) {
  100256. throw new Error(context + ": Failed to find index (" + index + ")");
  100257. }
  100258. return array[index];
  100259. };
  100260. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  100261. // Set defaults if undefined
  100262. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  100263. switch (mode) {
  100264. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  100265. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  100266. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  100267. default:
  100268. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  100269. return BABYLON.Texture.WRAP_ADDRESSMODE;
  100270. }
  100271. };
  100272. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  100273. // Set defaults if undefined
  100274. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  100275. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  100276. if (magFilter === 9729 /* LINEAR */) {
  100277. switch (minFilter) {
  100278. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  100279. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  100280. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  100281. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  100282. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  100283. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  100284. default:
  100285. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  100286. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  100287. }
  100288. }
  100289. else {
  100290. if (magFilter !== 9728 /* NEAREST */) {
  100291. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  100292. }
  100293. switch (minFilter) {
  100294. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  100295. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  100296. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  100297. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  100298. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  100299. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  100300. default:
  100301. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  100302. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  100303. }
  100304. }
  100305. };
  100306. GLTFLoader._GetNumComponents = function (context, type) {
  100307. switch (type) {
  100308. case "SCALAR": return 1;
  100309. case "VEC2": return 2;
  100310. case "VEC3": return 3;
  100311. case "VEC4": return 4;
  100312. case "MAT2": return 4;
  100313. case "MAT3": return 9;
  100314. case "MAT4": return 16;
  100315. }
  100316. throw new Error(context + ": Invalid type (" + type + ")");
  100317. };
  100318. GLTFLoader._ValidateUri = function (uri) {
  100319. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  100320. };
  100321. GLTFLoader._GetDrawMode = function (context, mode) {
  100322. if (mode == undefined) {
  100323. mode = 4 /* TRIANGLES */;
  100324. }
  100325. switch (mode) {
  100326. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  100327. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  100328. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  100329. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  100330. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  100331. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  100332. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  100333. }
  100334. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  100335. };
  100336. GLTFLoader.prototype._compileMaterialsAsync = function () {
  100337. var promises = new Array();
  100338. if (this._gltf.materials) {
  100339. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  100340. var material = _a[_i];
  100341. if (material._babylonData) {
  100342. for (var babylonDrawMode in material._babylonData) {
  100343. var babylonData = material._babylonData[babylonDrawMode];
  100344. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  100345. var babylonMesh = _c[_b];
  100346. // Ensure nonUniformScaling is set if necessary.
  100347. babylonMesh.computeWorldMatrix(true);
  100348. var babylonMaterial = babylonData.material;
  100349. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  100350. if (this.useClipPlane) {
  100351. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  100352. }
  100353. }
  100354. }
  100355. }
  100356. }
  100357. }
  100358. return Promise.all(promises).then(function () { });
  100359. };
  100360. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  100361. var promises = new Array();
  100362. var lights = this._babylonScene.lights;
  100363. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  100364. var light = lights_1[_i];
  100365. var generator = light.getShadowGenerator();
  100366. if (generator) {
  100367. promises.push(generator.forceCompilationAsync());
  100368. }
  100369. }
  100370. return Promise.all(promises).then(function () { });
  100371. };
  100372. GLTFLoader.prototype._clear = function () {
  100373. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  100374. var request = _a[_i];
  100375. request.abort();
  100376. }
  100377. this._requests.length = 0;
  100378. if (this._gltf && this._gltf.images) {
  100379. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  100380. var image = _c[_b];
  100381. if (image._objectURL) {
  100382. image._objectURL.then(function (value) {
  100383. URL.revokeObjectURL(value);
  100384. });
  100385. image._objectURL = undefined;
  100386. }
  100387. }
  100388. }
  100389. delete this._gltf;
  100390. delete this._babylonScene;
  100391. this._completePromises.length = 0;
  100392. for (var name_4 in this._extensions) {
  100393. this._extensions[name_4].dispose();
  100394. }
  100395. this._extensions = {};
  100396. delete this._rootBabylonMesh;
  100397. delete this._progressCallback;
  100398. this.onMeshLoadedObservable.clear();
  100399. this.onTextureLoadedObservable.clear();
  100400. this.onMaterialLoadedObservable.clear();
  100401. };
  100402. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  100403. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  100404. var name_5 = _a[_i];
  100405. var extension = this._extensions[name_5];
  100406. if (extension.enabled) {
  100407. var promise = actionAsync(extension);
  100408. if (promise) {
  100409. return promise;
  100410. }
  100411. }
  100412. }
  100413. return null;
  100414. };
  100415. GLTFLoader._Names = new Array();
  100416. GLTFLoader._Factories = {};
  100417. return GLTFLoader;
  100418. }());
  100419. GLTF2.GLTFLoader = GLTFLoader;
  100420. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  100421. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100422. })(BABYLON || (BABYLON = {}));
  100423. //# sourceMappingURL=babylon.glTFLoader.js.map
  100424. "use strict";
  100425. var BABYLON;
  100426. (function (BABYLON) {
  100427. var GLTF2;
  100428. (function (GLTF2) {
  100429. var GLTFLoaderExtension = /** @class */ (function () {
  100430. function GLTFLoaderExtension(loader) {
  100431. this.enabled = true;
  100432. this._loader = loader;
  100433. }
  100434. GLTFLoaderExtension.prototype.dispose = function () {
  100435. delete this._loader;
  100436. };
  100437. // #region Overridable Methods
  100438. /** Override this method to modify the default behavior for loading scenes. */
  100439. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  100440. /** Override this method to modify the default behavior for loading nodes. */
  100441. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  100442. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  100443. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  100444. /** Override this method to modify the default behavior for loading materials. */
  100445. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  100446. /** Override this method to modify the default behavior for loading uris. */
  100447. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  100448. // #endregion
  100449. /** Helper method called by a loader extension to load an glTF extension. */
  100450. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  100451. if (!property.extensions) {
  100452. return null;
  100453. }
  100454. var extensions = property.extensions;
  100455. var extension = extensions[this.name];
  100456. if (!extension) {
  100457. return null;
  100458. }
  100459. // Clear out the extension before executing the action to avoid recursing into the same property.
  100460. delete extensions[this.name];
  100461. try {
  100462. return actionAsync(context + "/extensions/" + this.name, extension);
  100463. }
  100464. finally {
  100465. // Restore the extension after executing the action.
  100466. extensions[this.name] = extension;
  100467. }
  100468. };
  100469. /** Helper method called by the loader to allow extensions to override loading scenes. */
  100470. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  100471. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  100472. };
  100473. /** Helper method called by the loader to allow extensions to override loading nodes. */
  100474. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  100475. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  100476. };
  100477. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  100478. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  100479. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  100480. };
  100481. /** Helper method called by the loader to allow extensions to override loading materials. */
  100482. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  100483. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  100484. };
  100485. /** Helper method called by the loader to allow extensions to override loading uris. */
  100486. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  100487. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  100488. };
  100489. return GLTFLoaderExtension;
  100490. }());
  100491. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  100492. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100493. })(BABYLON || (BABYLON = {}));
  100494. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  100495. "use strict";
  100496. var BABYLON;
  100497. (function (BABYLON) {
  100498. var GLTF2;
  100499. (function (GLTF2) {
  100500. var Extensions;
  100501. (function (Extensions) {
  100502. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  100503. var NAME = "MSFT_lod";
  100504. var MSFT_lod = /** @class */ (function (_super) {
  100505. __extends(MSFT_lod, _super);
  100506. function MSFT_lod() {
  100507. var _this = _super !== null && _super.apply(this, arguments) || this;
  100508. _this.name = NAME;
  100509. /**
  100510. * Maximum number of LODs to load, starting from the lowest LOD.
  100511. */
  100512. _this.maxLODsToLoad = Number.MAX_VALUE;
  100513. _this._loadingNodeLOD = null;
  100514. _this._loadNodeSignals = {};
  100515. _this._loadingMaterialLOD = null;
  100516. _this._loadMaterialSignals = {};
  100517. return _this;
  100518. }
  100519. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  100520. var _this = this;
  100521. return this._loadExtensionAsync(context, node, function (context, extension) {
  100522. var firstPromise;
  100523. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  100524. var _loop_1 = function (indexLOD) {
  100525. var nodeLOD = nodeLODs[indexLOD];
  100526. if (indexLOD !== 0) {
  100527. _this._loadingNodeLOD = nodeLOD;
  100528. if (!_this._loadNodeSignals[nodeLOD._index]) {
  100529. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  100530. }
  100531. }
  100532. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  100533. if (indexLOD !== 0) {
  100534. var previousNodeLOD = nodeLODs[indexLOD - 1];
  100535. if (previousNodeLOD._babylonMesh) {
  100536. previousNodeLOD._babylonMesh.dispose(false, true);
  100537. delete previousNodeLOD._babylonMesh;
  100538. }
  100539. }
  100540. if (indexLOD !== nodeLODs.length - 1) {
  100541. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  100542. if (_this._loadNodeSignals[nodeIndex]) {
  100543. _this._loadNodeSignals[nodeIndex].resolve();
  100544. delete _this._loadNodeSignals[nodeIndex];
  100545. }
  100546. }
  100547. });
  100548. if (indexLOD === 0) {
  100549. firstPromise = promise;
  100550. }
  100551. else {
  100552. _this._loader._completePromises.push(promise);
  100553. _this._loadingNodeLOD = null;
  100554. }
  100555. };
  100556. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  100557. _loop_1(indexLOD);
  100558. }
  100559. return firstPromise;
  100560. });
  100561. };
  100562. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100563. var _this = this;
  100564. // Don't load material LODs if already loading a node LOD.
  100565. if (this._loadingNodeLOD) {
  100566. return null;
  100567. }
  100568. return this._loadExtensionAsync(context, material, function (context, extension) {
  100569. var firstPromise;
  100570. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  100571. var _loop_2 = function (indexLOD) {
  100572. var materialLOD = materialLODs[indexLOD];
  100573. if (indexLOD !== 0) {
  100574. _this._loadingMaterialLOD = materialLOD;
  100575. if (!_this._loadMaterialSignals[materialLOD._index]) {
  100576. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  100577. }
  100578. }
  100579. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  100580. if (indexLOD !== 0) {
  100581. var babylonDataLOD = materialLOD._babylonData;
  100582. assign(babylonDataLOD[babylonDrawMode].material);
  100583. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  100584. if (previousBabylonDataLOD[babylonDrawMode]) {
  100585. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  100586. delete previousBabylonDataLOD[babylonDrawMode];
  100587. }
  100588. }
  100589. if (indexLOD !== materialLODs.length - 1) {
  100590. var materialIndex = materialLODs[indexLOD + 1]._index;
  100591. if (_this._loadMaterialSignals[materialIndex]) {
  100592. _this._loadMaterialSignals[materialIndex].resolve();
  100593. delete _this._loadMaterialSignals[materialIndex];
  100594. }
  100595. }
  100596. });
  100597. if (indexLOD === 0) {
  100598. firstPromise = promise;
  100599. }
  100600. else {
  100601. _this._loader._completePromises.push(promise);
  100602. _this._loadingMaterialLOD = null;
  100603. }
  100604. };
  100605. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  100606. _loop_2(indexLOD);
  100607. }
  100608. return firstPromise;
  100609. });
  100610. };
  100611. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  100612. var _this = this;
  100613. // Defer the loading of uris if loading a material or node LOD.
  100614. if (this._loadingMaterialLOD) {
  100615. var index = this._loadingMaterialLOD._index;
  100616. return this._loadMaterialSignals[index].promise.then(function () {
  100617. return _this._loader._loadUriAsync(context, uri);
  100618. });
  100619. }
  100620. else if (this._loadingNodeLOD) {
  100621. var index = this._loadingNodeLOD._index;
  100622. return this._loadNodeSignals[index].promise.then(function () {
  100623. return _this._loader._loadUriAsync(context, uri);
  100624. });
  100625. }
  100626. return null;
  100627. };
  100628. /**
  100629. * Gets an array of LOD properties from lowest to highest.
  100630. */
  100631. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  100632. if (this.maxLODsToLoad <= 0) {
  100633. throw new Error("maxLODsToLoad must be greater than zero");
  100634. }
  100635. var properties = new Array();
  100636. for (var i = ids.length - 1; i >= 0; i--) {
  100637. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  100638. if (properties.length === this.maxLODsToLoad) {
  100639. return properties;
  100640. }
  100641. }
  100642. properties.push(property);
  100643. return properties;
  100644. };
  100645. return MSFT_lod;
  100646. }(GLTF2.GLTFLoaderExtension));
  100647. Extensions.MSFT_lod = MSFT_lod;
  100648. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  100649. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100650. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100651. })(BABYLON || (BABYLON = {}));
  100652. //# sourceMappingURL=MSFT_lod.js.map
  100653. "use strict";
  100654. var BABYLON;
  100655. (function (BABYLON) {
  100656. var GLTF2;
  100657. (function (GLTF2) {
  100658. var Extensions;
  100659. (function (Extensions) {
  100660. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  100661. var NAME = "KHR_draco_mesh_compression";
  100662. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  100663. __extends(KHR_draco_mesh_compression, _super);
  100664. function KHR_draco_mesh_compression(loader) {
  100665. var _this = _super.call(this, loader) || this;
  100666. _this.name = NAME;
  100667. _this._dracoCompression = null;
  100668. // Disable extension if decoder is not available.
  100669. if (!BABYLON.DracoCompression.DecoderUrl) {
  100670. _this.enabled = false;
  100671. }
  100672. return _this;
  100673. }
  100674. KHR_draco_mesh_compression.prototype.dispose = function () {
  100675. if (this._dracoCompression) {
  100676. this._dracoCompression.dispose();
  100677. }
  100678. _super.prototype.dispose.call(this);
  100679. };
  100680. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  100681. var _this = this;
  100682. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  100683. if (primitive.mode != undefined) {
  100684. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  100685. primitive.mode !== 4 /* TRIANGLES */) {
  100686. throw new Error(context + ": Unsupported mode " + primitive.mode);
  100687. }
  100688. // TODO: handle triangle strips
  100689. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  100690. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  100691. }
  100692. }
  100693. var attributes = {};
  100694. var loadAttribute = function (name, kind) {
  100695. var uniqueId = extension.attributes[name];
  100696. if (uniqueId == undefined) {
  100697. return;
  100698. }
  100699. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  100700. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  100701. babylonMesh._delayInfo.push(kind);
  100702. }
  100703. attributes[kind] = uniqueId;
  100704. };
  100705. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  100706. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  100707. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  100708. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  100709. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  100710. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  100711. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  100712. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  100713. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  100714. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  100715. try {
  100716. if (!_this._dracoCompression) {
  100717. _this._dracoCompression = new BABYLON.DracoCompression();
  100718. }
  100719. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  100720. }
  100721. catch (e) {
  100722. throw new Error(context + ": " + e.message);
  100723. }
  100724. });
  100725. });
  100726. };
  100727. return KHR_draco_mesh_compression;
  100728. }(GLTF2.GLTFLoaderExtension));
  100729. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  100730. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  100731. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100732. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100733. })(BABYLON || (BABYLON = {}));
  100734. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  100735. "use strict";
  100736. var BABYLON;
  100737. (function (BABYLON) {
  100738. var GLTF2;
  100739. (function (GLTF2) {
  100740. var Extensions;
  100741. (function (Extensions) {
  100742. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  100743. var NAME = "KHR_materials_pbrSpecularGlossiness";
  100744. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  100745. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  100746. function KHR_materials_pbrSpecularGlossiness() {
  100747. var _this = _super !== null && _super.apply(this, arguments) || this;
  100748. _this.name = NAME;
  100749. return _this;
  100750. }
  100751. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100752. var _this = this;
  100753. return this._loadExtensionAsync(context, material, function (context, extension) {
  100754. material._babylonData = material._babylonData || {};
  100755. var babylonData = material._babylonData[babylonDrawMode];
  100756. if (!babylonData) {
  100757. var promises = new Array();
  100758. var name_1 = material.name || "materialSG_" + material._index;
  100759. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  100760. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  100761. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  100762. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  100763. babylonData = {
  100764. material: babylonMaterial,
  100765. meshes: [],
  100766. loaded: Promise.all(promises).then(function () { })
  100767. };
  100768. material._babylonData[babylonDrawMode] = babylonData;
  100769. }
  100770. babylonData.meshes.push(babylonMesh);
  100771. assign(babylonData.material);
  100772. return babylonData.loaded;
  100773. });
  100774. };
  100775. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  100776. var promises = new Array();
  100777. if (properties.diffuseFactor) {
  100778. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  100779. babylonMaterial.alpha = properties.diffuseFactor[3];
  100780. }
  100781. else {
  100782. babylonMaterial.albedoColor = BABYLON.Color3.White();
  100783. }
  100784. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  100785. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  100786. if (properties.diffuseTexture) {
  100787. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  100788. babylonMaterial.albedoTexture = texture;
  100789. }));
  100790. }
  100791. if (properties.specularGlossinessTexture) {
  100792. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  100793. babylonMaterial.reflectivityTexture = texture;
  100794. }));
  100795. babylonMaterial.reflectivityTexture.hasAlpha = true;
  100796. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  100797. }
  100798. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  100799. return Promise.all(promises).then(function () { });
  100800. };
  100801. return KHR_materials_pbrSpecularGlossiness;
  100802. }(GLTF2.GLTFLoaderExtension));
  100803. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  100804. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  100805. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100806. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100807. })(BABYLON || (BABYLON = {}));
  100808. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  100809. "use strict";
  100810. var BABYLON;
  100811. (function (BABYLON) {
  100812. var GLTF2;
  100813. (function (GLTF2) {
  100814. var Extensions;
  100815. (function (Extensions) {
  100816. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  100817. var NAME = "KHR_lights";
  100818. var LightType;
  100819. (function (LightType) {
  100820. LightType["AMBIENT"] = "ambient";
  100821. LightType["DIRECTIONAL"] = "directional";
  100822. LightType["POINT"] = "point";
  100823. LightType["SPOT"] = "spot";
  100824. })(LightType || (LightType = {}));
  100825. var KHR_lights = /** @class */ (function (_super) {
  100826. __extends(KHR_lights, _super);
  100827. function KHR_lights() {
  100828. var _this = _super !== null && _super.apply(this, arguments) || this;
  100829. _this.name = NAME;
  100830. return _this;
  100831. }
  100832. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  100833. var _this = this;
  100834. return this._loadExtensionAsync(context, scene, function (context, extension) {
  100835. var promise = _this._loader._loadSceneAsync(context, scene);
  100836. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  100837. if (light.type !== LightType.AMBIENT) {
  100838. throw new Error(context + ": Only ambient lights are allowed on a scene");
  100839. }
  100840. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  100841. return promise;
  100842. });
  100843. };
  100844. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  100845. var _this = this;
  100846. return this._loadExtensionAsync(context, node, function (context, extension) {
  100847. var promise = _this._loader._loadNodeAsync(context, node);
  100848. var babylonLight;
  100849. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  100850. var name = node._babylonMesh.name;
  100851. switch (light.type) {
  100852. case LightType.AMBIENT: {
  100853. throw new Error(context + ": Ambient lights are not allowed on a node");
  100854. }
  100855. case LightType.DIRECTIONAL: {
  100856. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  100857. break;
  100858. }
  100859. case LightType.POINT: {
  100860. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  100861. break;
  100862. }
  100863. case LightType.SPOT: {
  100864. var spotLight = light;
  100865. // TODO: support inner and outer cone angles
  100866. //const innerConeAngle = spotLight.innerConeAngle || 0;
  100867. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  100868. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  100869. break;
  100870. }
  100871. default: {
  100872. throw new Error(context + ": Invalid light type (" + light.type + ")");
  100873. }
  100874. }
  100875. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  100876. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  100877. babylonLight.parent = node._babylonMesh;
  100878. return promise;
  100879. });
  100880. };
  100881. Object.defineProperty(KHR_lights.prototype, "_lights", {
  100882. get: function () {
  100883. var extensions = this._loader._gltf.extensions;
  100884. if (!extensions || !extensions[this.name]) {
  100885. throw new Error("#/extensions: '" + this.name + "' not found");
  100886. }
  100887. var extension = extensions[this.name];
  100888. return extension.lights;
  100889. },
  100890. enumerable: true,
  100891. configurable: true
  100892. });
  100893. return KHR_lights;
  100894. }(GLTF2.GLTFLoaderExtension));
  100895. Extensions.KHR_lights = KHR_lights;
  100896. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  100897. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100898. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100899. })(BABYLON || (BABYLON = {}));
  100900. //# sourceMappingURL=KHR_lights.js.map
  100901. return BABYLON;
  100902. });
  100903. /***/ }),
  100904. /* 34 */
  100905. /***/ (function(module, exports, __webpack_require__) {
  100906. /*!
  100907. * PEP v0.4.3 | https://github.com/jquery/PEP
  100908. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  100909. */
  100910. !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);
  100911. // define inherited MouseEvent properties
  100912. // skip bubbles and cancelable since they're set above in initEvent()
  100913. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  100914. // Spec requires that pointers without pressure specified use 0.5 for down
  100915. // state and 0 for up state.
  100916. var f=0;
  100917. // add x/y properties aliased to clientX/Y
  100918. // define the properties of the PointerEvent interface
  100919. 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(){
  100920. // only activate if this platform does not have pointer events
  100921. 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}})}/**
  100922. * This is the constructor for new PointerEvents.
  100923. *
  100924. * New Pointer Events must be given a type, and an optional dictionary of
  100925. * initialization properties.
  100926. *
  100927. * Due to certain platform requirements, events returned from the constructor
  100928. * identify as MouseEvents.
  100929. *
  100930. * @constructor
  100931. * @param {String} inType The type of the event to create.
  100932. * @param {Object} [inDict] An optional dictionary of initial event properties.
  100933. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  100934. */
  100935. 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},
  100936. // return value, key, map
  100937. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  100938. // MouseEvent
  100939. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  100940. // DOM Level 3
  100941. "buttons",
  100942. // PointerEvent
  100943. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  100944. // event instance
  100945. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  100946. // MouseEvent
  100947. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  100948. // DOM Level 3
  100949. 0,
  100950. // PointerEvent
  100951. 0,0,0,0,0,0,"",0,!1,
  100952. // event instance
  100953. "",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),
  100954. // Scope objects for native events.
  100955. // This exists for ease of testing.
  100956. eventSources:Object.create(null),eventSourceList:[],/**
  100957. * Add a new event source that will generate pointer events.
  100958. *
  100959. * `inSource` must contain an array of event names named `events`, and
  100960. * functions with the names specified in the `events` array.
  100961. * @param {string} name A name for the event source
  100962. * @param {Object} source A new source of platform events.
  100963. */
  100964. 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++)
  100965. // call eventsource register
  100966. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  100967. // call eventsource register
  100968. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  100969. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  100970. return!1}},
  100971. // EVENTS
  100972. 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)},
  100973. // LISTENER LOGIC
  100974. eventHandler:function(a){
  100975. // This is used to prevent multiple dispatch of pointerevents from
  100976. // platform events. This can happen when two elements in different scopes
  100977. // are set up to create pointer events, which is relevant to Shadow DOM.
  100978. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  100979. // set up event listeners
  100980. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  100981. // remove event listeners
  100982. 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)},
  100983. // EVENT CREATION AND TRACKING
  100984. /**
  100985. * Creates a new Event of type `inType`, based on the information in
  100986. * `inEvent`.
  100987. *
  100988. * @param {string} inType A string representing the type of event to create
  100989. * @param {Event} inEvent A platform event with a target
  100990. * @return {Event} A PointerEvent of type `inType`
  100991. */
  100992. makeEvent:function(b,c){
  100993. // relatedTarget must be null if pointer is captured
  100994. 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},
  100995. // make and dispatch an event in one call
  100996. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  100997. * Returns a snapshot of inEvent, with writable properties.
  100998. *
  100999. * @param {Event} inEvent An event that contains properties to copy.
  101000. * @return {Object} An object containing shallow copies of `inEvent`'s
  101001. * properties.
  101002. */
  101003. 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],
  101004. // Work around SVGInstanceElement shadow tree
  101005. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  101006. // This is the behavior implemented by Firefox.
  101007. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  101008. // keep the semantics of preventDefault
  101009. 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){
  101010. // Order of conditions due to document.contains() missing in IE.
  101011. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  101012. // Touch: Do not propagate if node is detached.
  101013. 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)}},/**
  101014. * Dispatches the event to its target.
  101015. *
  101016. * @param {Event} inEvent The event to be dispatched.
  101017. * @return {Boolean} True if an event handler returns true, false otherwise.
  101018. */
  101019. 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(
  101020. // is element a shadow host?
  101021. e=this.targetingShadow(f);e;){if(
  101022. // find the the element inside the shadow root
  101023. d=e.elementFromPoint(b,c)){
  101024. // shadowed element may contain a shadow root
  101025. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  101026. // check for older shadows
  101027. e=this.olderShadow(e)}
  101028. // light dom element is the target
  101029. return f}},owner:function(a){
  101030. // walk up until you hit the shadow root or document
  101031. for(var b=a;b.parentNode;)b=b.parentNode;
  101032. // the owner element is expected to be a Document or ShadowRoot
  101033. 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);
  101034. // if x, y is not in this root, fall back to document search
  101035. 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){
  101036. // Only watch scopes that can target find, as these are top-level.
  101037. // Otherwise we can see duplicate additions and removals that add noise.
  101038. //
  101039. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  101040. // a removal without an insertion when a node is redistributed among
  101041. // shadows. Since it all ends up correct in the document, watching only
  101042. // the document will yield the correct mutations to watch.
  101043. 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))},
  101044. // register all touch-action = none nodes on document load
  101045. 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){
  101046. // find children with touch-action
  101047. var b=x(a,this.findElements,this);
  101048. // flatten the list
  101049. // make sure the added nodes are accounted for
  101050. 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){}
  101051. // handler block for native mouse events
  101052. 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:[],
  101053. // collide with the global mouse listener
  101054. 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++){
  101055. // simulated mouse events will be swallowed near a primary touchend
  101056. 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);
  101057. // Update buttons state after possible out-of-document mouseup.
  101058. 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];
  101059. // Produces wrong state of buttons in Browsers without `buttons` support
  101060. // when a mouse button that was pressed outside the document is released
  101061. // inside and other buttons are still pressed down.
  101062. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  101063. // Support: Firefox <=44 only
  101064. // FF Ubuntu includes the lifted button in the `buttons` property on
  101065. // mouseup.
  101066. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  101067. 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),
  101068. // set touch-action on shadows as well
  101069. 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),
  101070. // remove touch-action from shadow
  101071. 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);
  101072. // simply update scrollType if listeners are already established
  101073. 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){
  101074. // set primary touch if there no pointers, or the only pointer is the mouse
  101075. (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,
  101076. // forward modifier keys
  101077. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  101078. // forward touch preventDefaults
  101079. 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))},
  101080. // For single axis scrollers, determines whether the element should emit
  101081. // pointer events or behave as a scroller
  101082. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  101083. // this element is a touch-action: none, should never scroll
  101084. b=!1;else if("XY"===c)
  101085. // this element should always scroll
  101086. 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]);
  101087. // if delta in the scroll axis > delta other axis, scroll instead of
  101088. // making events
  101089. 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},
  101090. // In some instances, a touchstart can happen without a touchend. This
  101091. // leaves the pointermap in a broken state.
  101092. // Therefore, on every touchstart, we remove the touches that did not fire a
  101093. // touchend event.
  101094. // To keep state globally consistent, we fire a
  101095. // pointercancel for this "abandoned" touch
  101096. vacuumTouches:function(a){var b=a.touches;
  101097. // pointermap.size should be < tl.length here, as the touchstart has not
  101098. // been processed yet.
  101099. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  101100. // Never remove pointerId == 1, which is mouse.
  101101. // Touch identifiers are 2 smaller than their pointerId, which is the
  101102. // index in pointermap.
  101103. 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);
  101104. // a finger drifted off the screen, ignore it
  101105. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  101106. // recover from retargeting by shadow
  101107. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  101108. // clean up case when finger leaves the screen
  101109. 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)},
  101110. // prevent synth mouse events from creating pointer events
  101111. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  101112. // only the primary finger will synth mouse events
  101113. if(this.isPrimaryTouch(c)){
  101114. // remember x/y of last touch
  101115. 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});
  101116. /***/ }),
  101117. /* 35 */
  101118. /***/ (function(module, exports, __webpack_require__) {
  101119. "use strict";
  101120. Object.defineProperty(exports, "__esModule", { value: true });
  101121. var defaultViewer_1 = __webpack_require__(5);
  101122. var mappers_1 = __webpack_require__(1);
  101123. function InitTags(selector) {
  101124. if (selector === void 0) { selector = 'babylon'; }
  101125. var elements = document.querySelectorAll(selector);
  101126. for (var i = 0; i < elements.length; ++i) {
  101127. var element = elements.item(i);
  101128. var configMapper = mappers_1.mapperManager.getMapper('dom');
  101129. var config = configMapper.map(element);
  101130. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  101131. }
  101132. }
  101133. exports.InitTags = InitTags;
  101134. /***/ })
  101135. /******/ ]);
  101136. return BabylonViewer;
  101137. });